iOS-了解一下方法調(diào)用和消息轉(zhuǎn)發(fā)流程

前言

  • 發(fā)布此文章主要是對(duì)自己所學(xué)知識(shí)的總結(jié)
  • 通過文章的方式可以讓自己對(duì)所學(xué)知識(shí)加深印象
  • 方便日后需要的時(shí)候查看,如果有不對(duì)的地方歡迎指出
  • 文筆不行,多多見諒

更詳細(xì)一點(diǎn)可以去看看霜神的神經(jīng)病院Objective-C Runtime住院第二天——消息發(fā)送與轉(zhuǎn)發(fā)

整個(gè)方法調(diào)用流程共分為3個(gè)階段:

  • 消息發(fā)送
  • 動(dòng)態(tài)方法解析
  • 消息轉(zhuǎn)發(fā)

objc_msgSend()

要說對(duì)象,我相信世界上沒有比程序員的對(duì)象多的了,因?yàn)槲覀兠刻於紩?huì)newN個(gè)對(duì)象,而且想讓它干什么它就干什么,不用給它買車買房,偶爾有時(shí)候發(fā)個(gè)小脾氣(bug),敲會(huì)鍵盤就收拾他們了,根本就不用哄,最主要的是我可以指揮它
怎么指揮它的呢?發(fā)送消息唄!

        MyGirlFriend *girlFriend = [[MyGirlFriend alloc]init];
        
        [girlFriend goCooking];

編譯成c++代碼
((void (*)(id, SEL))(void *)objc_msgSend)((id)girlFriend, sel_registerName("goCooking"));
調(diào)用了objc_msgSend(id self, SEL op, ...)函數(shù),去源碼中看看這貨到底干了寫啥,在objc-msg-arm64.s中查找ENTRY _objc_msgSend

    ENTRY _objc_msgSend
    UNWIND _objc_msgSend, NoFrame
    MESSENGER_START

    cmp x0, #0          // nil check and tagged pointer check
    b.le    LNilOrTagged        //  (MSB tagged pointer looks negative)
    ldr x13, [x0]       // x13 = isa
    and x16, x13, #ISA_MASK // x16 = class  
LGetIsaDone:
    CacheLookup NORMAL      // calls imp or objc_msgSend_uncached

LNilOrTagged:
    b.eq    LReturnZero     // nil check

    // tagged
    mov x10, #0xf000000000000000
    cmp x0, x10
    b.hs    LExtTag
    adrp    x10, _objc_debug_taggedpointer_classes@PAGE
    add x10, x10, _objc_debug_taggedpointer_classes@PAGEOFF
    ubfx    x11, x0, #60, #4
    ldr x16, [x10, x11, LSL #3]
    b   LGetIsaDone

LExtTag:
    // ext tagged
    adrp    x10, _objc_debug_taggedpointer_ext_classes@PAGE
    add x10, x10, _objc_debug_taggedpointer_ext_classes@PAGEOFF
    ubfx    x11, x0, #52, #8
    ldr x16, [x10, x11, LSL #3]
    b   LGetIsaDone
    
LReturnZero:
    // x0 is already zero
    mov x1, #0
    movi    d0, #0
    movi    d1, #0
    movi    d2, #0
    movi    d3, #0
    MESSENGER_END_NIL
    ret

    END_ENTRY _objc_msgSend

cmp x0,檢查消息接收者是否為空
b.eq LReturnZero: 如果為空就跳轉(zhuǎn)到LReturnZero
LReturnZero: ret 返回
如果消息接收者不為nil
CacheLookup:在緩存中查找SEL

.macro CacheLookup
    // x1 = SEL, x16 = isa
    ldp x10, x11, [x16, #CACHE] // x10 = buckets, x11 = occupied|mask
    and w12, w1, w11        // x12 = _cmd & mask
    add x12, x10, x12, LSL #4   // x12 = buckets + ((_cmd & mask)<<4)

    ldp x9, x17, [x12]      // {x9, x17} = *bucket
1:  cmp x9, x1          // if (bucket->sel != _cmd)
    b.ne    2f          //     scan more
    CacheHit $0         // call or return imp
    
2:  // not hit: x12 = not-hit bucket
    CheckMiss $0            // miss if bucket->sel == 0
    cmp x12, x10        // wrap if bucket == buckets
    b.eq    3f
    ldp x9, x17, [x12, #-16]!   // {x9, x17} = *--bucket
    b   1b          // loop

3:  // wrap: x12 = first bucket, w11 = mask
    add x12, x12, w11, UXTW #4  // x12 = buckets+(mask<<4)

    // Clone scanning loop to miss instead of hang when cache is corrupt.
    // The slow path may detect any corruption and halt later.

    ldp x9, x17, [x12]      // {x9, x17} = *bucket
1:  cmp x9, x1          // if (bucket->sel != _cmd)
    b.ne    2f          //     scan more
    CacheHit $0         // call or return imp
    
2:  // not hit: x12 = not-hit bucket
    CheckMiss $0            // miss if bucket->sel == 0
    cmp x12, x10        // wrap if bucket == buckets
    b.eq    3f
    ldp x9, x17, [x12, #-16]!   // {x9, x17} = *--bucket
    b   1b          // loop

3:  // double wrap
    JumpMiss $0
    
.endmacro

看注釋可以看出幾個(gè)比較關(guān)鍵的buckets,_cmd & mask,可以大膽的猜一下,這是在從buckets這個(gè)散列數(shù)組中用 _cmd&mask找到對(duì)應(yīng)的方法緩存,不了解這幾個(gè)的可以去類的結(jié)構(gòu)中的cache中查看哦
這段代碼主要作用是:查緩存,在cache中查找_cmd對(duì)象的實(shí)現(xiàn)IMP
CacheHit $0 // call or return imp:命中調(diào)用或者返回IMP
CheckMiss $0 // miss if bucket->sel == 0:沒有命中

.macro CheckMiss
    // miss if bucket->sel == 0
.if $0 == GETIMP
    cbz x9, LGetImpMiss
.elseif $0 == NORMAL
    cbz x9, __objc_msgSend_uncached
.elseif $0 == LOOKUP
    cbz x9, __objc_msgLookup_uncached
.else
.abort oops
.endif
.endmacro

傳入的是NORMAL,會(huì)調(diào)用__objc_msgSend_uncached

STATIC_ENTRY __objc_msgSend_uncached
    UNWIND __objc_msgSend_uncached, FrameWithNoSaves

    // THIS IS NOT A CALLABLE C FUNCTION
    // Out-of-band x16 is the class to search
    
    MethodTableLookup
    br  x17

    END_ENTRY __objc_msgSend_uncached

調(diào)用MethodTableLookup,

.macro MethodTableLookup
    bl  __class_lookupMethodAndLoadCache3
.endmacro

去掉一個(gè)_搜索一下_class_lookupMethodAndLoadCache3;

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

在runtime-new.mm中找到,后面的下面再說,先小節(jié)一下
通過上面的混編代碼,總結(jié)如下:在調(diào)用objc_msgSend時(shí),會(huì)先判斷消息接收者是不是nil,如果是nil直接返回,如果有在方法緩存中查找SEL,如果緩存可以找到就直接返回活調(diào)用IMP,如果沒有找到,就去類對(duì)象或者元類對(duì)象的方法列表中查找;

一 : 消息發(fā)送

依然還是從源碼中著手,接著上面的看吧

// Try this class's cache.試著在類的緩存中查找

    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.在這個(gè)類的父類的方法列表中查找
    {
        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 {
                    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;
            }
        }
    }
  • 在本類的方法緩存中查找,如果找到就返回
  • 上面沒有找到就到類的方法列表中查找
  • 在父類的緩存和方法列表中查找
    先看看怎么在方法列表中查找的?
getMethodNoSuper_nolock(Class cls, SEL sel)
{
    for (auto mlists = cls->data()->methods.beginLists(), 
              end = cls->data()->methods.endLists(); 
         mlists != end;
         ++mlists)
    {
        method_t *m = search_method_list(*mlists, sel);
        if (m) return m;
    }
    return nil;
}
static method_t *search_method_list(const method_list_t *mlist, SEL sel)
{
    int methodListIsFixedUp = mlist->isFixedUp();
    int methodListHasExpectedSize = mlist->entsize() == sizeof(method_t);
    
    if (__builtin_expect(methodListIsFixedUp && methodListHasExpectedSize, 1)) {
        return findMethodInSortedMethodList(sel, mlist);
    } else {
        // Linear search of unsorted method list
        for (auto& meth : *mlist) {
            if (meth.name == sel) return &meth;
        }
    }
    return nil;
}
static method_t *findMethodInSortedMethodList(SEL key, const method_list_t *list)
{
    assert(list);
    const method_t * const first = &list->first;
    const method_t *base = first;
    const method_t *probe;
    uintptr_t keyValue = (uintptr_t)key;
    uint32_t count;
    //count>>=1也就是count = count>>1;右移一位比如10,右移一位就是5了,大家可以試試1010右移一位等于0101
    for (count = list->count; count != 0; count >>= 1) {
        probe = base + (count >> 1);
        
        uintptr_t probeValue = (uintptr_t)probe->name;
        
        if (keyValue == probeValue) {
            while (probe > first && keyValue == (uintptr_t)probe[-1].name) {
                probe--;
            }
            return (method_t *)probe;
        }
        if (keyValue > probeValue) {
            base = probe + 1;
            count--;
        }
    }
    return nil;
}
  • 循環(huán)遍歷class_rw_t里面的methods,獲取到method_list_t
  • 通過search_method_list函數(shù)遍歷出method_t(方法的結(jié)構(gòu)體),如果有序就進(jìn)行二分查找,如果無(wú)序就常規(guī)循環(huán)遍歷
  • 最終如果IMP有值就直接返回method_t結(jié)構(gòu)體指針
if (meth) {
            log_and_fill_cache(cls, meth->imp, sel, inst, cls);//打印并緩存imp
            imp = meth->imp;//獲取method_t里的imp并返回
            goto done;
        }

如果找到IMP就對(duì)IMP進(jìn)行緩存,并返回,沒有找到就去父類中查找
首先查看緩存cache_getImp找到就緩存在本類的緩存中,并返回IMP
緩存中沒有繼續(xù)在方法列表中查找,步驟和在類中查找一樣
如果還沒有查找到就開始進(jìn)行動(dòng)態(tài)方法解析

消息發(fā)送

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

通過上面一系列的查找調(diào)用,如果還沒有找到對(duì)象的IMP,蘋果還是比較仁慈的,允許你進(jìn)行補(bǔ)救,也就是動(dòng)態(tài)方法解析,可以在合適的位置動(dòng)態(tài)的為這個(gè)類添加方法,一起看看吧!

// No implementation found. Try method resolver once.
//沒有找到方法實(shí)現(xiàn),嘗試使用一次解析器
    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;
    }
void _class_resolveMethod(Class cls, SEL sel, id inst)
{
    if (! cls->isMetaClass()) {
        // try [cls resolveInstanceMethod:sel]
        _class_resolveInstanceMethod(cls, sel, inst);
    } 
    else {
        // try [nonMetaClass resolveClassMethod:sel]
        // and [cls resolveInstanceMethod:sel]
        _class_resolveClassMethod(cls, sel, inst);
        if (!lookUpImpOrNil(cls, sel, inst, 
                            NO/*initialize*/, YES/*cache*/, NO/*resolver*/)) 
        {
            _class_resolveInstanceMethod(cls, sel, inst);
        }
    }
}

進(jìn)入動(dòng)態(tài)解析階段會(huì)去調(diào)用兩個(gè)方法,如果傳入的是類對(duì)象就調(diào)用+ (BOOL)resolveClassMethod:(SEL)sel,如果是元類對(duì)象就調(diào)用+ (BOOL)resolveInstanceMethod:(SEL)sel
,如果什么都不做返回NO,如果在這里動(dòng)態(tài)的添加方法,返回YES
動(dòng)態(tài)添加方法實(shí)現(xiàn)的三種方式

//第一種方式,自定義結(jié)構(gòu)體,獲取到method對(duì)象賦值給結(jié)構(gòu)體
struct method_t {
    SEL sel;
    char *types;
    IMP imp;
};
- (void)other
{
    NSLog(@"%s",__func__);
}
+(BOOL)resolveInstanceMethod:(SEL)sel
{
    if (sel == @selector(test)) {

        struct method_t *method = (struct method_t *)class_getInstanceMethod(self, @selector(other));
        class_addMethod(self, sel, method->imp, method->types);

        return YES;
    }

    return [super resolveInstanceMethod:sel];
}
//第二種方式.,直接通過函數(shù)去獲取相關(guān)信息
+ (BOOL)resolveInstanceMethod:(SEL)sel
{
    if (sel == @selector(test)) {

        Method method = class_getInstanceMethod(self, @selector(other));

        class_addMethod(self, sel, method_getImplementation(method), method_getTypeEncoding(method));
        return YES;
    }
    return [super resolveInstanceMethod:sel];
}

//第三種方式
- (void)other
{
    NSLog(@"%s",__func__);
}
+ (BOOL)resolveInstanceMethod:(SEL)sel
{
    if (sel == @selector(test)) {

        class_addMethod(self, sel, (IMP)c_other, "v16@0:8");
        return YES;
    }
    return [super resolveInstanceMethod:sel];
}

調(diào)用了上面的方法然后調(diào)用goto retry;再走一次消息發(fā)送流程
如果沒有進(jìn)行動(dòng)態(tài)方法解析,就繼續(xù)向下走咯,消息轉(zhuǎn)發(fā)

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

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

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

到這里SEL還是沒有找到對(duì)應(yīng)的IMP,對(duì)象方法可以重寫- (id)forwardingTargetForSelector:(SEL)aSelector,類方法+ (id)forwardingTargetForSelector:(SEL)aSelector,把消息的接受者換成一個(gè)可以處理該消息的對(duì)象。

- (id)forwardingTargetForSelector:(SEL)aSelector
{
    if (aSelector == @selector(goCooking)) {
        return "可以處理消息的實(shí)例對(duì)象";
    }
    return [super forwardingTargetForSelector:aSelector];
}
+ (id)forwardingTargetForSelector:(SEL)aSelector
{
    if (aSelector == @selector(goCooking)) {
        return "可以處理消息的類對(duì)象"
    }
    return [super forwardingTargetForSelector:aSelector];
}

如果這一步返回的是nil,Runtime系統(tǒng)會(huì)向?qū)ο蟀l(fā)送methodSignatureForSelector:消息,并取到返回的方法簽名用于生成NSInvocation對(duì)象。為接下來的完整的消息轉(zhuǎn)發(fā)生成一個(gè) NSMethodSignature對(duì)象。NSMethodSignature 對(duì)象會(huì)被包裝成 NSInvocation 對(duì)象,forwardInvocation: 方法里就可以對(duì) NSInvocation 進(jìn)行處理了

- (NSMethodSignature *)methodSignatureForSelector:(SEL)aSelector
{
    if (aSelector == @selector(test)) {

        return [NSMethodSignature signatureWithObjCTypes:"v16@0:8"];
//        return nil;
    }
    return [super methodSignatureForSelector:aSelector];
}
- (void)forwardInvocation:(NSInvocation *)anInvocation
{
    XXObject *xxobjc = [[XXObject alloc]init];
    anInvocation.target = xxobjc;
    if ([xxobjc respondsToSelector:anInvocation.selector]) {
        [anInvocation invoke];
    }else{
        [super forwardInvocation:anInvocation];
    }
}

如果XXObject處理不了的話,就去父類找,一直找到NSObject,還不能處理這個(gè)消息的話,就只能拋出“doesNotRecognizeSelector”異常了。

消息發(fā)送與轉(zhuǎn)發(fā)流程

理解了消息發(fā)送轉(zhuǎn)發(fā)的機(jī)制.對(duì)以后的工作和閱讀別人源碼有很大的幫助,作為iOS開發(fā)者也有必要對(duì)底層原理多一些了解,這也是很多面試中經(jīng)常被問到的問題,希望我的這些廢話,沒有誤人子弟,如有錯(cuò)誤歡迎提出

請(qǐng)大家多多支持,在此謝過!!!

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

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