1、首先簡單說一下OC消息發(fā)送機(jī)制
消息發(fā)送分兩步:
第一步,編譯階段
不帶參數(shù):objc_msgSend(receiver,selector)
帶參數(shù):objc_msgSend(recevier,selector,org1,org2,…)
在這一階段確定消息接受者receiver和要去執(zhí)行的方法selector,這時候不會去確定方法是否實(shí)現(xiàn)。
第二步,運(yùn)行時階段
運(yùn)行時階段的消息發(fā)送的詳細(xì)步驟如下:
- 如果selector、target兩個都是有效的,那就開始查找這個類的 IMP,先從 cache 里面找,若可以找得到就跳到對應(yīng)的函數(shù)去執(zhí)行。
- 如果在cache里找不到就找一下方法列表methodLists。
- 如果methodLists找不到,就到超類的方法列表里尋找,一直找,直到找到NSObject類為止。
- 如果還找不到,Runtime就提供了如下三種方法來處理:動態(tài)方法解析、消息接受者重定向、消息重定向,這三者就不具體介紹了,不懂的網(wǎng)上自行百度。

2、NSProxy的介紹
Apple 官方文檔
NSProxy is an abstract superclass defining an API for objects that act as stand-ins for other objects or for objects that don’t exist yet. Typically, a message to a proxy is forwarded to the real object or causes the proxy to load (or transform itself into) the real object. Subclasses of NSProxy can be used to implement transparent distributed messaging (for example, NSDistantObject) or for lazy instantiation of objects that are expensive to create.
NSProxy 是一個抽象基類,它是為一些作為對象的替身或者并不存在的對象定義的API。一般的,發(fā)送給代理的消息被轉(zhuǎn)發(fā)給一個真實(shí)的對象或者代理本身引起加載(或者將本身轉(zhuǎn)換成)一個真實(shí)的對象。NSProxy的基類可以被用來透明的轉(zhuǎn)發(fā)消息或者耗費(fèi)巨大的對象的lazy 初始化。
NSProxy我理解的其實(shí)它就是一個消息重定向封裝的一個抽象類,類似一個代理人、中間件??梢酝ㄟ^繼承它,并重寫下面這兩個方法來實(shí)現(xiàn)消息轉(zhuǎn)發(fā)到另一個實(shí)例。
- (void)forwardInvocation:(NSInvocation *)invocation;
- (nullable NSMethodSignature *)methodSignatureForSelector:(SEL)sel
3、NSProxy的使用
- 實(shí)現(xiàn)多繼承的功能
- 解決了NSTimer&CADisplayLink創(chuàng)建時對self強(qiáng)引用問題,參考YYKit的YYWeakProxy。