runtime源碼解析(二) 方法調(diào)用

寫在前面

前面說了Runtime源碼解析(一) 方法加載。既然方法都加載好了,那么現(xiàn)在就來說說方法調(diào)用。大家基本上都知道[receiver message]會被翻譯為 objc_msgSend(receiver, @selector(message))。不過在說這個前想先說說+initialize方法。為什么要先說它呢?因為在類或它的子類收到第一條消息之前會調(diào)用initialize方法,這里所指的消息包括實例方法和類方法的調(diào)用。而且這個方法是以懶加載的方式被調(diào)用的。

+initialize

initialize的調(diào)用棧:_objc_msgSend_uncached -> _class_lookupMethodAndLoadCache3 -> lookUpImpOrForward -> _class_initialize -> callInitialize{也就是((void(*)(Class, SEL))objc_msgSend)(cls, SEL_initialize) }

下面我們一個個來看看這些方法
正常情況是objc_msgSend,但是在initialize之前沒有cache,所以會變成_objc_msgSend_uncached(匯編寫的)。_class_lookupMethodAndLoadCache3就是調(diào)用了lookUpImpOrForward。下面主要說說這個方法

// 這個方法非常關(guān)鍵,就是查找方法的,返回IMP
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) {
        imp = cache_getImp(cls, sel); // 先看有沒有緩存,有的話直接返回
        if (imp) return imp;
    }
    runtimeLock.read();
    if (!cls->isRealized()) {  // 現(xiàn)在這里時候,這個代碼塊不會走的,因為方法加載的時候已經(jīng)isRealized過了
        runtimeLock.unlockRead();
        runtimeLock.write();
        realizeClass(cls);
        runtimeLock.unlockWrite();
        runtimeLock.read();
    }
    if (initialize  &&  !cls->isInitialized()) {
        runtimeLock.unlockRead();
        _class_initialize (_class_getNonMetaClass(cls, inst));  // 這里就是initialize方法,第一次發(fā)送方法前會走這個代碼塊
        runtimeLock.read();
    }    
 retry:    
    runtimeLock.assertReading();
    imp = cache_getImp(cls, sel);
    if (imp) goto done;
    {
        Method meth = getMethodNoSuper_nolock(cls, sel);  // 在當(dāng)前類的方法列表中查找
        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;
             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 {
                    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.unlockRead();
        // Jack 動態(tài)方法解析
        _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.
    // Jack 消息轉(zhuǎn)發(fā)
    imp = (IMP)_objc_msgForward_impcache;
    cache_fill(cls, sel, imp, inst);
 done:
    runtimeLock.unlockRead();
    return imp;
}

lookUpImpOrForward是個是很重要的方法,里面還有的方法我就不展開說了,下面開始說說消息轉(zhuǎn)發(fā)流程。(如果在正常的方法列表里沒有查找到方法,就進(jìn)入消息轉(zhuǎn)發(fā)流程)

消息轉(zhuǎn)發(fā)

首先是動態(tài)方法解析,_class_resolveMethod里面又調(diào)用了_class_resolveInstanceMethod

static void _class_resolveInstanceMethod(Class cls, SEL sel, id inst)
{
    // 查找類是否實現(xiàn)了+ (BOOL)resolveInstanceMethod:(SEL)sel方法
    // 如果沒有實現(xiàn)就直接返回
    if (! lookUpImpOrNil(cls->ISA(), SEL_resolveInstanceMethod, cls, 
                         NO/*initialize*/, YES/*cache*/, NO/*resolver*/)) 
    {
        // Resolver not implemented.
        return;
    }
    BOOL (*msg)(Class, SEL, SEL) = (__typeof__(msg))objc_msgSend;
    bool resolved = msg(cls, SEL_resolveInstanceMethod, sel);
    // Cache the result (good or bad) so the resolver doesn't fire next time.
    // +resolveInstanceMethod adds to self a.k.a. cls
  // 調(diào)用類里面實現(xiàn)的+ (BOOL)resolveInstanceMethod:(SEL)sel
    IMP imp = lookUpImpOrNil(cls, sel, inst, 
                             NO/*initialize*/, YES/*cache*/, NO/*resolver*/);
}

總結(jié)

最后匯總一下正常方法調(diào)用的過程,總的來看還是很合情合理的:

  • 查找當(dāng)前類的緩存和方法列表
  • 查找父類的緩存和方法列表
  • 動態(tài)方法解析
  • 消息轉(zhuǎn)發(fā)
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

推薦閱讀更多精彩內(nèi)容

  • 轉(zhuǎn)至元數(shù)據(jù)結(jié)尾創(chuàng)建: 董瀟偉,最新修改于: 十二月 23, 2016 轉(zhuǎn)至元數(shù)據(jù)起始第一章:isa和Class一....
    40c0490e5268閱讀 1,774評論 0 9
  • 文中的實驗代碼我放在了這個項目中。 以下內(nèi)容是我通過整理[這篇博客] (http://yulingtianxia....
    茗涙閱讀 946評論 0 6
  • 消息發(fā)送和轉(zhuǎn)發(fā)流程可以概括為:消息發(fā)送(Messaging)是 Runtime 通過 selector 快速查找 ...
    lylaut閱讀 1,896評論 2 3
  • 我們常常會聽說 Objective-C 是一門動態(tài)語言,那么這個「動態(tài)」表現(xiàn)在哪呢?我想最主要的表現(xiàn)就是 Obje...
    Ethan_Struggle閱讀 2,231評論 0 7
  • 轉(zhuǎn)載:http://yulingtianxia.com/blog/2014/11/05/objective-c-r...
    F麥子閱讀 768評論 0 2