runtime(二)--發(fā)消息和消息轉(zhuǎn)發(fā)

1. objc方法調(diào)用的過(guò)程大致分為兩步:
  1. 從objc_msgSend()開(kāi)始,查找方法過(guò)程,俗稱發(fā)消息
  2. 如果方法找不到,則進(jìn)入消息轉(zhuǎn)發(fā)機(jī)制
2. objc_msgSend()方法

2.1 這個(gè)方法其實(shí)有5個(gè)變體

方法名 作用
objc_msgSend 一般方法
objc_msgSend_stret 返回結(jié)構(gòu)體類型數(shù)據(jù)
objc_msgSend_fpret 返回float類型數(shù)據(jù)
objc_msgSendSuper 父類方法調(diào)用
objc_msgSendSuper_stret 父類方法調(diào)用,同時(shí)返回結(jié)構(gòu)體類型數(shù)據(jù)

參考:Apple 官方文檔

When it encounters a method call, the compiler generates a call to one of the functions objc_msgSend, objc_msgSend_stret, objc_msgSendSuper, or objc_msgSendSuper_stret. Messages sent to an object’s superclass (using the super keyword) are sent using objc_msgSendSuper; other messages are sent using objc_msgSend. Methods that have data structures as return values are sent using objc_msgSendSuper_stret and objc_msgSend_stret.

2.2 配置runtime 源碼可運(yùn)行環(huán)境
看了一些博客及官方文檔,覺(jué)得還是看源碼這樣更清晰,源碼面前無(wú)秘密

2.3 消息發(fā)送過(guò)程,涉及兩個(gè)方法_class_lookupMethodAndLoadCache3和lookUpImpOrForward

  1. 配置oc運(yùn)行代碼如下:
#import "Test.h"

int main(int argc, const char * argv[]) {
    @autoreleasepool {
        Test *test = [Test new];
        [test say]; 
    }
    return 0;
}
  1. 方法的調(diào)用堆棧截圖如下:


    [test say]方法調(diào)用堆棧截圖
  2. 可以看到
    1>先走了_objc_msgSend_uncached方法,該方法是一個(gè)匯編方法,接下來(lái)調(diào)用了_class_lookupMethodAndLoadCache3方法,指定不同的initialize,cache,resolver給lookUpImpOrForward方法,所以核心邏輯在lookUpImpOrForward方法里
    (據(jù)我斷點(diǎn)調(diào)試,當(dāng)再次調(diào)用同一個(gè)方法時(shí),不管是同一個(gè)對(duì)象或者新生成一個(gè)對(duì)象調(diào)用,都不會(huì)再執(zhí)行上邊過(guò)程,所以下述分析只針對(duì)方法第一次調(diào)用的情況)

IMP _class_lookupMethodAndLoadCache3(id obj, SEL sel, Class cls)
{
    return lookUpImpOrForward(cls, sel, obj, 
                              YES/*initialize*/, NO/*cache*/, YES/*resolver*/);
}

2>lookUpImpOrForward方法的作用就是查找和轉(zhuǎn)發(fā),由名字也可以看出;流程就是就是先找cache,找不到再?gòu)念悓?duì)象、父類對(duì)象->元類->根元類中找,找到之后會(huì)cache;找到根元類還找不到,就開(kāi)始消息轉(zhuǎn)發(fā)流程

IMP lookUpImpOrForward(Class cls, SEL sel, id inst, 
                       bool initialize, bool cache, bool resolver)
{
    IMP imp = nil;
    bool triedResolver = NO;

    runtimeLock.assertUnlocked();

    // Optimistic cache lookup
    if (cache) { //判斷是否已緩存,第一次不會(huì)走這里
        imp = cache_getImp(cls, sel);
        if (imp) return imp;
    }

    // runtimeLock is held during isRealized and isInitialized checking
    // to prevent races against concurrent realization.

    // runtimeLock is held during method search to make
    // method-lookup + cache-fill atomic with respect to method addition.
    // Otherwise, a category could be added but ignored indefinitely because
    // the cache was re-filled with the old value after the cache flush on
    // behalf of the category.

    runtimeLock.read(); //使用了runtime讀寫(xiě)鎖

    if (!cls->isRealized()) {
        // Drop the read-lock and acquire the write-lock.
        // realizeClass() checks isRealized() again to prevent
        // a race while the lock is down.
        runtimeLock.unlockRead();
        runtimeLock.write();

        realizeClass(cls);  //if塊中主要是該方法

        runtimeLock.unlockWrite();
        runtimeLock.read();
    }

    if (initialize  &&  !cls->isInitialized()) {
        runtimeLock.unlockRead();
        _class_initialize (_class_getNonMetaClass(cls, inst)); // 主要是該方法
        runtimeLock.read();
        // If sel == initialize, _class_initialize will send +initialize and 
        // then the messenger will send +initialize again after this 
        // procedure finishes. Of course, if this is not being called 
        // from the messenger then it won't happen. 2778172
    }

    
 retry:    
    runtimeLock.assertReading();

    // Try this class's cache.

    imp = cache_getImp(cls, sel); //重新嘗試cache,推測(cè)是因?yàn)榧恿随i的緣故,再次走到這里時(shí),cache中可能已經(jīng)有了,算是一個(gè)優(yōu)化策略
    if (imp) goto done;

    // Try this class's method lists.  //從類對(duì)象中獲取找到method,找到之后緩存
    {
        Method meth = getMethodNoSuper_nolock(cls, sel);
        if (meth) {
            log_and_fill_cache(cls, meth->imp, sel, inst, cls);
            imp = meth->imp;
            goto done;
        }
    }

    // Try superclass caches and method lists. // 從父類中找,使用for循環(huán)不停向上遍歷
    {
        unsigned attempts = unreasonableClassCount();
        for (Class curClass = cls->superclass;
             curClass != nil;
             curClass = curClass->superclass)
        {
            // Halt if there is a cycle in the superclass chain.
            if (--attempts == 0) {
                _objc_fatal("Memory corruption in class list.");
            }
            
            // Superclass cache.
            imp = cache_getImp(curClass, sel); //跟上方邏輯基本一致,先找cache,再?gòu)念悓?duì)象中找;
            if (imp) {
                if (imp != (IMP)_objc_msgForward_impcache) {
                    // Found the method in a superclass. Cache it in this class.
                    log_and_fill_cache(cls, imp, sel, inst, curClass);
                    goto done;
                }
                else {
                    // Found a forward:: entry in a superclass.
                    // Stop searching, but don't cache yet; call method 
                    // resolver for this class first.
                    break;
                }
            }
            
            // Superclass method list.
            Method meth = getMethodNoSuper_nolock(curClass, sel);
            if (meth) {
                log_and_fill_cache(cls, meth->imp, sel, inst, curClass);
                imp = meth->imp;
                goto done;
            }
        }
    }

    // No implementation found. Try method resolver once.
   // 上邊都找不到,就開(kāi)始消息轉(zhuǎn)發(fā)流程了
  // 1.先進(jìn)行消息解析,即runtime的兩個(gè)resolve方法,解析成功的話,再走一遍查找流程
  // 2.解析失敗,再執(zhí)行forward,forward又分兩步
  // 2.1 forwardingTargetForSelector交給其他對(duì)象去執(zhí)行
  // 2.2 forwardInvocation將@selector封裝成一個(gè)NSInvocation對(duì)象,作為最后的執(zhí)行機(jī)會(huì)
    if (resolver  &&  !triedResolver) {
        runtimeLock.unlockRead();
        _class_resolveMethod(cls, sel, inst);
        runtimeLock.read();
        // Don't cache the result; we don't hold the lock so it may have 
        // changed already. Re-do the search from scratch instead.
        triedResolver = YES;
        goto retry;
    }

    // No implementation found, and method resolver didn't help. 
    // Use forwarding.
   // 開(kāi)始消息轉(zhuǎn)發(fā)
    imp = (IMP)_objc_msgForward_impcache; // 沒(méi)有找到該方法的源碼,要不然消息轉(zhuǎn)發(fā)的調(diào)用過(guò)程我們也可以很清晰了
    cache_fill(cls, sel, imp, inst);

 done:
    runtimeLock.unlockRead();

    return imp;
}

可以用偽代碼幫助理解:

// 1. 判斷是否要初始化對(duì)象
if(!cls->initialized()){
  _class_initialize();
}
// 2. 開(kāi)始查找
while(cls){
  // 1. 查找緩存 
  imp = cache_getImp();
 // 2. 緩存中沒(méi)有,找方法列表
  if(!imp){
  Method meth = getMethodNoSuper_nolock();
  if(Method){
    return meth->imp;
  }
  cls = cls->superClass;
  }
}
// 3. 方法沒(méi)找到,先進(jìn)行方法解析
Bool flag = _class_resolveMethod(cls, sel, inst);
// 4. 解析失敗,轉(zhuǎn)發(fā)消息
if(!flag){
  _objc_msgForward_impcache();
}
3. 消息轉(zhuǎn)發(fā)機(jī)制

由上述方法中可以看到_objc_msgForward_impcache這個(gè)IMP開(kāi)啟了消息轉(zhuǎn)發(fā)過(guò)程,不過(guò)該IMP沒(méi)有實(shí)現(xiàn)源碼,怎么確定接下來(lái)過(guò)程呢?
有兩個(gè)方案:

  1. 用instrumentObjcMessageSends(YES)來(lái)打印所有消息到文件中,參考:runtime 拾遺,我測(cè)試發(fā)現(xiàn)出現(xiàn)崩潰,輸出的"/private/tmp/msgSends-進(jìn)程id"文件是空的,與runtime鎖機(jī)制有關(guān),暫不知道解決辦法,崩潰日志如下;
objc[4492]: lock 0x1008c53c0 (runtimeLock) acquired before 0x1008c5340 (objcMsgLogLock) with no defined lock order
  1. 重寫(xiě)自定義類的resolveClassMethod、forwardingTargetForSelector等方法,然后分別加斷點(diǎn),可以通過(guò)調(diào)用堆棧來(lái)確定流程
    此處我采用第二種方式,得到的結(jié)果與第一種方式應(yīng)該是一樣的,重寫(xiě)的代碼如下:
+ (BOOL)resolveInstanceMethod:(SEL)sel{
    return NO;
}
-(id)forwardingTargetForSelector:(SEL)aSelector{
    return [super forwardingTargetForSelector:aSelector];
}
- (NSMethodSignature *)methodSignatureForSelector:(SEL)aSelector{
    if([NSStringFromSelector(aSelector) isEqualToString:@"say"]){ 
        return [NSMethodSignature signatureWithObjCTypes:"v@:"];
    }else{
        return [super methodSignatureForSelector:aSelector];
    }
}
- (void)forwardInvocation:(NSInvocation *)anInvocation{ //該方法默認(rèn)不執(zhí)行,需要重寫(xiě)methodSignatureForSelector返回指定的方法簽名才會(huì)進(jìn)
    [super forwardInvocation:anInvocation];
}
  1. 經(jīng)過(guò)我斷點(diǎn)調(diào)試,上邊方法調(diào)用順序如下:
    resolveInstanceMethod->
    forwardingTargetForSelector->
    methodSignatureForSelector->
    resolveInstanceMethod-> //此處會(huì)多一次方法解析,與lookUpImpOrForward里的邏輯有關(guān)
    forwardInvocation->
    崩潰
    也就是注明的這張圖


    消息轉(zhuǎn)發(fā)流程
  2. 附一個(gè)resolveInstanceMethod方法第一次調(diào)用堆棧:


    resolveInstanceMethod堆棧
3. 消息轉(zhuǎn)發(fā)一些理解:
  1. doesNotRecognizeSelector:會(huì)在控制臺(tái)出現(xiàn)是因?yàn)楫?dāng)前類沒(méi)有實(shí)現(xiàn)該方法,而基類NSObject forwardInvocation:方法實(shí)現(xiàn)中拋出了doesNotRecognizeSelector:異常,可以通過(guò)runtime的源碼證明
- (void)forwardInvocation:(NSInvocation *)invocation {
    [self doesNotRecognizeSelector:(invocation ? [invocation selector] : 0)];
}
- (void)doesNotRecognizeSelector:(SEL)sel {
    _objc_fatal("-[%s %s]: unrecognized selector sent to instance %p", 
                object_getClassName(self), sel_getName(sel), self);
}
  1. 防止unrecognized selector崩潰,可以有3種方式:
  • 在resolveInstanceMethod方法中add一個(gè)方法實(shí)現(xiàn)
  • 在forwardingTargetForSelector方法中轉(zhuǎn)給其他對(duì)象實(shí)現(xiàn)
  • 在forwardInvocation中轉(zhuǎn)給其他對(duì)象實(shí)現(xiàn)
  • 還可以重寫(xiě)doesNotRecognizeSelector來(lái)實(shí)現(xiàn),原理是:參考上邊一條注釋,最終調(diào)用的當(dāng)前類的doesNotRecognizeSelector實(shí)現(xiàn),在該實(shí)現(xiàn)中不拋出異常就可以了,比如這樣
- (void)doesNotRecognizeSelector:(SEL)aSelector{
    NSString *selStr = NSStringFromSelector(aSelector);
    NSLog(@"%@不存在",selStr);
}

參考這篇文章:iOS 消息轉(zhuǎn)發(fā)機(jī)制Demo解析

  1. 利用消息轉(zhuǎn)發(fā)可以實(shí)現(xiàn)類似多繼承的效果,因?yàn)榭梢詫⑾⑥D(zhuǎn)發(fā)給其他對(duì)象,就像是其他對(duì)象成了當(dāng)前對(duì)象的基類一樣。

參考:從源代碼看 ObjC 中消息的發(fā)送

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容