iOS 消息發(fā)送機(jī)制

通過(guò)前篇知道了,消息發(fā)送最后會(huì)來(lái)到這里。整體實(shí)現(xiàn)是下面這樣:

IMP _class_lookupMethodAndLoadCache3(id obj, SEL sel, Class cls)
{
    return lookUpImpOrForward(cls, sel, obj, 
                              YES/*initialize*/, NO/*cache*/, YES/*resolver*/);
}
IMP lookUpImpOrForward(Class cls, SEL sel, id inst, 
                       bool initialize, bool cache, bool resolver)
{
    IMP imp = nil; //方法實(shí)現(xiàn)地址
    bool triedResolver = NO; //是否嘗試了方法解析

    runtimeLock.assertUnlocked();

    // Optimistic cache lookup
    if (cache) {
        imp = cache_getImp(cls, sel);
        if (imp) return imp;
    }

    runtimeLock.lock(); 
    checkIsKnownClass(cls); //檢查是否是已知類,如果是false則會(huì)拋出錯(cuò)誤

    // 下面是對(duì)類的一個(gè)初始化
    
    if (!cls->isRealized()) {
        realizeClass(cls);
    }
    if (initialize  &&  !cls->isInitialized()) {
        runtimeLock.unlock();
        _class_initialize (_class_getNonMetaClass(cls, inst));
        runtimeLock.lock();
        // 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.assertLocked();

    // Try this class's cache.
    // 緩存獲取imp
    imp = cache_getImp(cls, sel);
    if (imp) goto done;

    // Try this class's method lists.
    {
        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.
    {
        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);
            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.

    if (resolver  &&  !triedResolver) {
        runtimeLock.unlock();
        _class_resolveMethod(cls, sel, inst);
        runtimeLock.lock();
        // 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.

    imp = (IMP)_objc_msgForward_impcache;
    cache_fill(cls, sel, imp, inst);

 done:
    runtimeLock.unlock();

    return imp;
}

1.首先主要看這一段

流程:
1.先在當(dāng)前類緩存中查找, 沒(méi)有找到則去當(dāng)前類的方法列表中查找,找到直接返回,找到將方法存儲(chǔ)到cache中
2.如果找不到則通過(guò)isa找到父類,在父類的cache里面查找,找不到則在父類的方法列表中查找,找到直接返回,找到將方法存儲(chǔ)到cache中
3.一直找到循環(huán)3
4.如果一直到不到則進(jìn)入動(dòng)態(tài)方法解析


------------------- 1. 當(dāng)前類方法中查找 --------------------

    // 在緩存中查找
    imp = cache_getImp(cls, sel);
    //如果找到就直接返回函數(shù)的IMP
    if (imp) goto done;
    //2.在這個(gè)類的方法列表里面尋找
    // Try this class's method lists.
    {
        //查找方法
        Method meth = getMethodNoSuper_nolock(cls, sel);
        if (meth) {
        //存儲(chǔ)方法到緩存中
            log_and_fill_cache(cls, meth->imp, sel, inst, cls);
            imp = meth->imp;
            goto done;
        }
    }
    
    
    
    ----------------- 2. 父類查找 --------------------
    
    
    // Try superclass caches and method lists.
    {
    // 循環(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.");
            }
            
            //父類的cache中查找
            imp = cache_getImp(curClass, sel);
            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;
                }
            }
            
            //父類方法列表中查找
            Method meth = getMethodNoSuper_nolock(curClass, sel);
            if (meth) {
            //找到存儲(chǔ)到當(dāng)前類的cache中
                log_and_fill_cache(cls, meth->imp, sel, inst, curClass);
                imp = meth->imp;
                goto done;
            }
        }
    }
    

動(dòng)態(tài)方法解析

動(dòng)態(tài)方法解析可以看到 triedResolver = YES, goto retry;發(fā)現(xiàn)代碼還會(huì)再次走一遍消息查找上面的流程,由于triedResolver = YES所以不會(huì)再進(jìn)入動(dòng)態(tài)方法解析

// No implementation found. Try method resolver once.

//resolver == YES 是傳參過(guò)來(lái)的
// triedResolver剛進(jìn)來(lái)的時(shí)候是NO
    if (resolver  &&  !triedResolver) {
        runtimeLock.unlock();
        _class_resolveMethod(cls, sel, inst);
        runtimeLock.lock();
        // 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;
    }

2.動(dòng)態(tài)方法解析會(huì)調(diào)用當(dāng)前類的下面的方法
在方法里面動(dòng)態(tài)添加方法就不會(huì)class_addMethod,就會(huì)進(jìn)入到添加方法的這個(gè)里面

//對(duì)象方法進(jìn)入
+ (BOOL)resolveClassMethod:(SEL)sel {
    //在這里動(dòng)態(tài)添加方法
// 第一個(gè)參數(shù)是object_getClass(self)
class_addMethod(object_getClass(self), sel, (IMP)c_other, "v16@0:8");
    return [super resolveClassMethod:sel];
}

//類方法
+ (BOOL)resolveInstanceMethod:(SEL)sel {
    //在這里動(dòng)態(tài)添加方法
    return [super resolveInstanceMethod:sel];
}

3.消息轉(zhuǎn)發(fā)
消息轉(zhuǎn)發(fā)會(huì)進(jìn)入下面三個(gè)方法:

1.判斷是否調(diào)用forwardingTargetForSelector 方法,如果該方法返回消息轉(zhuǎn)發(fā)的接受者A,然后對(duì)返回的消息接受者發(fā)送消息objc_msgSend(A,SEL),如果沒(méi)有返回則進(jìn)行下一步
2.查看是否調(diào)用methodSignatureForSelector,如果調(diào)用,則返回NSMethodSignature這個(gè)類的對(duì)象,對(duì)象里面填寫方法的參數(shù)編碼(例如[a test]: v16@0:8),并且還要實(shí)現(xiàn)forwardInvocation這個(gè)方法,如果沒(méi)有實(shí)現(xiàn)forwardInvocation,則跳轉(zhuǎn)到最后調(diào)用doesNotRecognizeSelector報(bào)沒(méi)有找到方法的錯(cuò),如果實(shí)現(xiàn)了forwardInvocation,則不會(huì)報(bào)錯(cuò),還可以拿到調(diào)用方法的接受者,參數(shù),返回值

- (id)forwardingTargetForSelector:(SEL)aSelector {
    return [super forwardingTargetForSelector:aSelector];
}

-(NSMethodSignature *)methodSignatureForSelector:(SEL)aSelector {
    
    return [super methodSignatureForSelector:aSelector];
}

-(void)forwardInvocation:(NSInvocation *)anInvocation {

     return [super forwardInvocation:anInvocation];
}

參考:Objective-C 消息發(fā)送與轉(zhuǎn)發(fā)機(jī)制原理

熱愛(ài)生活,記錄生活!

?著作權(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)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

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

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