iOS-底層原理09-msgSend消息查找流程&動態(tài)方法決議

《iOS底層原理文章匯總》

如果在緩存中沒查找到方法腋颠,之后的流程,CheckMiss和JumpMiss的流程一模一樣

CheckMiss-->__objc_msgSend_uncached

.macro CheckMiss
    // miss if bucket->sel == 0
.if $0 == GETIMP
    cbz p9, LGetImpMiss
.elseif $0 == NORMAL
    cbz p9, __objc_msgSend_uncached
.elseif $0 == LOOKUP
    cbz p9, __objc_msgLookup_uncached

JumpMiss->__objc_msgSend_uncached-> MethodTableLookup->_lookUpImpOrForward

.macro JumpMiss
.if $0 == GETIMP
    b   LGetImpMiss
.elseif $0 == NORMAL
    b   __objc_msgSend_uncached
.elseif $0 == LOOKUP
    b   __objc_msgLookup_uncached

跳入MethodTableLookup

.endmacro

    STATIC_ENTRY __objc_msgSend_uncached
    UNWIND __objc_msgSend_uncached, FrameWithNoSaves

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

    END_ENTRY __objc_msgSend_uncached

_lookUpImpOrForward

.macro MethodTableLookup
    
    SAVE_REGS

    // lookUpImpOrForward(obj, sel, cls, LOOKUP_INITIALIZE | LOOKUP_RESOLVER)
    // receiver and selector already in x0 and x1
    mov x2, x16
    mov x3, #3
    bl  _lookUpImpOrForward

    // IMP in x0
    mov x17, x0

    RESTORE_REGS
    .endmacro

通過代碼跑流程的形式查看最終一個方法找不到會走入的流程

通過Debug workflow -> Always show disassembly -> 按住control + stepinto進入匯編調試

23.gif

定位到lookUpImpOrForward at objc-runtime-new.mm:6099行代碼

IMP lookUpImpOrForward(id inst, SEL sel, Class cls, int behavior)
{
    const IMP forward_imp = (IMP)_objc_msgForward_impcache;
    IMP imp = nil;
    Class curClass;

    runtimeLock.assertUnlocked();

    // Optimistic cache lookup
    if (fastpath(behavior & LOOKUP_CACHE)) {
        imp = cache_getImp(cls, sel);
        if (imp) goto done_nolock;
    }

    // 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.lock();

    // We don't want people to be able to craft a binary blob that looks like
    // a class but really isn't one and do a CFI attack.
    //
    // To make these harder we want to make sure this is a class that was
    // either built into the binary or legitimately registered through
    // objc_duplicateClass, objc_initializeClassPair or objc_allocateClassPair.
    //
    // TODO: this check is quite costly during process startup.
    checkIsKnownClass(cls);

    if (slowpath(!cls->isRealized())) {
        cls = realizeClassMaybeSwiftAndLeaveLocked(cls, runtimeLock);
        // runtimeLock may have been dropped but is now locked again
    }

    if (slowpath((behavior & LOOKUP_INITIALIZE) && !cls->isInitialized())) {
        cls = initializeAndLeaveLocked(cls, inst, runtimeLock);
        // runtimeLock may have been dropped but is now locked again

        // 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
    }

    runtimeLock.assertLocked();
    curClass = cls;

    // The code used to lookpu the class's cache again right after
    // we take the lock but for the vast majority of the cases
    // evidence shows this is a miss most of the time, hence a time loss.
    //
    // The only codepath calling into this without having performed some
    // kind of cache lookup is class_getInstanceMethod().

    for (unsigned attempts = unreasonableClassCount();;) {
        // curClass method list.
        Method meth = getMethodNoSuper_nolock(curClass, sel);
        if (meth) {
            imp = meth->imp;
            goto done;
        }

        if (slowpath((curClass = curClass->superclass) == nil)) {
            // No implementation found, and method resolver didn't help.
            // Use forwarding.
            imp = forward_imp;
            break;
        }

        // Halt if there is a cycle in the superclass chain.
        if (slowpath(--attempts == 0)) {
            _objc_fatal("Memory corruption in class list.");
        }

        // Superclass cache.
        imp = cache_getImp(curClass, sel); // 有問題???? cache_getImp - lookup - lookUpImpOrForward
        if (slowpath(imp == forward_imp)) {
            // Found a forward:: entry in a superclass.
            // Stop searching, but don't cache yet; call method
            // resolver for this class first.
            break;
        }
        if (fastpath(imp)) {
            // Found the method in a superclass. Cache it in this class.
            goto done;
        }
    }

    // No implementation found. Try method resolver once.

    if (slowpath(behavior & LOOKUP_RESOLVER)) {
        behavior ^= LOOKUP_RESOLVER;
        return resolveMethod_locked(inst, sel, cls, behavior);
    }

 done:
    log_and_fill_cache(cls, imp, sel, inst, curClass);
    runtimeLock.unlock();
 done_nolock:
    if (slowpath((behavior & LOOKUP_NIL) && imp == forward_imp)) {
        return nil;
    }
    return imp;
}

探索對象方法的查找流程

對象調用一個沒有實現的方法會報錯,方法的查找流程是轴猎,先從本類中查找,本類中沒有往父類中查找

#pragma clang diagnostic push
// 讓編譯器忽略錯誤
#pragma clang diagnostic ignored "-Wundeclared-selector"
        LGStudent *student = [[LGStudent alloc] init];
        // 對象方法
        [student sayHello];
        [student sayNB];
        // unrecognized selector sent to instance 0x103d32010
        [student sayMaster];
    
輸出
2020-11-01 11:25:58.294977+0800 002-方法的查找流程[22988:295515] -[LGStudent sayHello]
2020-11-01 11:25:58.295465+0800 002-方法的查找流程[22988:295515] -[LGPerson sayNB]
2020-11-01 11:25:58.295722+0800 002-方法的查找流程[22988:295515] -[LGStudent sayMaster]: unrecognized selector sent to instance 0x100622470
2020-11-01 11:25:58.296273+0800 002-方法的查找流程[22988:295515] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[LGStudent sayMaster]: unrecognized selector sent to instance 0x100622470'
*** First throw call stack:
(
    0   CoreFoundation                      0x00007fff31e89b57 __exceptionPreprocess + 250
    1   libobjc.A.dylib                     0x00007fff6acd05bf objc_exception_throw + 48
    2   CoreFoundation                      0x00007fff31f08be7 -[NSObject(NSObject) __retain_OA] + 0
    3   CoreFoundation                      0x00007fff31dee3bb ___forwarding___ + 1427
    4   CoreFoundation                      0x00007fff31dedd98 _CF_forwarding_prep_0 + 120
    
    6   libdyld.dylib                       0x00007fff6be78cc9 start + 1
)
libc++abi.dylib: terminating with uncaught exception of type NSException

若在NSObject中添加分類來實現sayMaster方法质欲,則方法能找到

@interface NSObject (LGCate)
- (void)sayMaster;
- (void)sayEasy;
@end
@implementation NSObject (LGCate)
- (void)sayMaster{
   NSLog(@"%s",__func__);
}
- (void)sayEasy{
    NSLog(@"%s",__func__);
}
@end

//輸出
2020-11-01 11:37:31.406340+0800 002-方法的查找流程[30058:313811] -[LGStudent sayHello]
2020-11-01 11:37:31.406764+0800 002-方法的查找流程[30058:313811] -[LGPerson sayNB]
2020-11-01 11:37:31.406844+0800 002-方法的查找流程[30058:313811] -[NSObject(LGCate) sayMaster]

如果是類中的一個類方法沒有實現呢绑嘹?

LGStudent中沒有類方法sayEasy,運行會報錯*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '+[LGStudent sayEasy]: unrecognized selector sent to class 0x100002290'
如果在NSObject分類中添加對象方法sayEasy郭脂,會不會報錯年碘?

// 類方法
[LGStudent sayObjc];
[LGStudent sayHappay];
[LGStudent performSelector:@selector(sayEasy)]; // +
        
@interface NSObject (LGCate)
- (void)sayMaster;
- (void)sayEasy;
@end

@implementation NSObject (LGCate)
- (void)sayMaster{
   NSLog(@"%s",__func__);
}
- (void)sayEasy{
    NSLog(@"%s",__func__);
}
@end

//輸出
2020-11-01 11:49:25.780317+0800 002-方法的查找流程[37381:333382] -[LGStudent sayHello]
2020-11-01 11:49:25.780738+0800 002-方法的查找流程[37381:333382] -[LGPerson sayNB]
2020-11-01 11:49:25.780785+0800 002-方法的查找流程[37381:333382] -[NSObject(LGCate) sayMaster]
2020-11-01 11:49:25.780817+0800 002-方法的查找流程[37381:333382] +[LGStudent sayObjc]
2020-11-01 11:49:25.780846+0800 002-方法的查找流程[37381:333382] +[LGPerson sayHappay]
2020-11-01 11:49:25.780877+0800 002-方法的查找流程[37381:333382] -[NSObject(LGCate) sayEasy]

根據ISA走位圖


isa流程圖.png

得到對象方法的查找流程

類->父類->NSObject->nil

類方法的查找流程,類方法存在元類里面
類方法在元類中是以對象方法的形式存在的

元類->父元類->根元類->NSObject->nil

NSObject分類中存在sayEasy的對象方法展鸡,即能找到屿衅,萬物皆會找到NSObject里面,Root class meta(NSObject)中沒有找到sayEasy的對象方法莹弊,則找根元類的父類Root class(NSObject)的實例方法涤久,因為繼承關系

方法的慢速查找流程

方法的慢速查找流程.png

通過閱讀源碼理解方法的慢速查找流程
lookUpImpOrForward

  • 1.獲取多線程中是否存在緩存的Imp,若存在可理解返回imp = cache_getImp(cls, sel);
  • 2.判斷類是否已知checkIsKnownClass(cls);
  • 3.判斷類是否實現和類checkIsKnownClass(cls);
  • 4.進行二分查找獲取類中方法的總數忍弛,進行遞歸
    for (unsigned attempts = unreasonableClassCount();;) {
        // curClass method list.
        //本類中查找
        Method meth = getMethodNoSuper_nolock(curClass, sel);
        if (meth) {
            imp = meth->imp;
            goto done;
        }

        //當前的類賦值為父類
        if (slowpath((curClass = curClass->superclass) == nil)) {
            // No implementation found, and method resolver didn't help.
            // Use forwarding.
            imp = forward_imp;
            break;
        }

        // Halt if there is a cycle in the superclass chain.
        if (slowpath(--attempts == 0)) {
            _objc_fatal("Memory corruption in class list.");
        }

        // Superclass cache.
        //從父類的緩存中查找
        imp = cache_getImp(curClass, sel);
        if (slowpath(imp == forward_imp)) {
            // Found a forward:: entry in a superclass.
            // Stop searching, but don't cache yet; call method
            // resolver for this class first.
            break;
        }
        if (fastpath(imp)) {
            // Found the method in a superclass. Cache it in this class.
            goto done;
        }
    }

先從本類中查找响迂,二分查找

@interface LGPerson : NSObject
@property (nonatomic, copy) NSString *lgName;
@property (nonatomic, strong) NSString *nickName;
- (void)sayNB;
- (void)sayMaster;
- (void)say666;
- (void)sayHello;
@end
@implementation LGPerson
- (void)sayHello{
    NSLog(@"%s",__func__);
}

- (void)sayNB{
    NSLog(@"%s",__func__);
}
- (void)sayMaster{
    NSLog(@"%s",__func__);
}
- (void)say666{
    NSLog(@"%s",__func__);
}
@end

從上面可以得知類中含有8個方法,分別為sayHello,sayNB,sayMaster,say666细疚,setLgName:,setNickName:,lgName,nickName;

ALWAYS_INLINE static method_t *
search_method_list_inline(const method_list_t *mlist, SEL sel)
{
    int methodListIsFixedUp = mlist->isFixedUp();
    int methodListHasExpectedSize = mlist->entsize() == sizeof(method_t);
    
    if (fastpath(methodListIsFixedUp && methodListHasExpectedSize)) {
        return findMethodInSortedMethodList(sel, mlist);
    } else {
        // Linear search of unsorted method list
        for (auto& meth : *mlist) {
            if (meth.name == sel) return &meth;
        }
    }

#if DEBUG
    // sanity-check negative results
    if (mlist->isFixedUp()) {
        for (auto& meth : *mlist) {
            if (meth.name == sel) {
                _objc_fatal("linear search worked when binary search did not");
            }
        }
    }
#endif

    return nil;
}

ALWAYS_INLINE 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;
    
    for (count = list->count; count != 0; count >>= 1) {
        probe = base + (count >> 1);
        
        uintptr_t probeValue = (uintptr_t)probe->name;
        
        if (keyValue == probeValue) {
            // `probe` is a match.
            // Rewind looking for the *first* occurrence of this value.
            // This is required for correct category overrides.
            while (probe > first && keyValue == (uintptr_t)probe[-1].name) {
                probe--;
            }
            return (method_t *)probe;
        }
        
        if (keyValue > probeValue) {
            base = probe + 1;
            count--;
        }
    }
    
    return nil;
}

通過調試mlist存在9個方法蔗彤,除了類中的8個方法外多了一個C++方法.cxx_destruct
(lldb) p mlist
(const method_list_t *) $0 = 0x00000001000020c8
(lldb) p *$0
(const method_list_t) $1 = {
  entsize_list_tt<method_t, method_list_t, 3> = {
    entsizeAndFlags = 26
    count = 9
    first = {
      name = "sayHello"
      types = 0x0000000100000f86 "v16@0:8"
      imp = 0x0000000100000c40 (KCObjc`-[LGPerson sayHello])
    }
  }
}
(lldb) p $1.get(0)
(method_t) $2 = {
  name = "sayHello"
  types = 0x0000000100000f86 "v16@0:8"
  imp = 0x0000000100000c40 (KCObjc`-[LGPerson sayHello])
}
(lldb) p $1.get(1)
(method_t) $3 = {
  name = "say666"
  types = 0x0000000100000f86 "v16@0:8"
  imp = 0x0000000100000cd0 (KCObjc`-[LGPerson say666])
}
(lldb) p $1.get(2)
(method_t) $4 = {
  name = "sayNB"
  types = 0x0000000100000f86 "v16@0:8"
  imp = 0x0000000100000c70 (KCObjc`-[LGPerson sayNB])
}
(lldb) p $1.get(3)
(method_t) $5 = {
  name = "sayMaster"
  types = 0x0000000100000f86 "v16@0:8"
  imp = 0x0000000100000ca0 (KCObjc`-[LGPerson sayMaster])
}
(lldb) p $1.get(4)
(method_t) $6 = {
  name = "lgName"
  types = 0x0000000100000f8e "@16@0:8"
  imp = 0x0000000100000d00 (KCObjc`-[LGPerson lgName])
}
(lldb) p $1.get(5)
(method_t) $7 = {
  name = "setLgName:"
  types = 0x0000000100000f96 "v24@0:8@16"
  imp = 0x0000000100000d30 (KCObjc`-[LGPerson setLgName:])
}
(lldb) p $1.get(6)
(method_t) $8 = {
  name = ".cxx_destruct"
  types = 0x0000000100000f86 "v16@0:8"
  imp = 0x0000000100000db0 (KCObjc`-[LGPerson .cxx_destruct])
}
(lldb) p $1.get(7)
(method_t) $9 = {
  name = "setNickName:"
  types = 0x0000000100000f96 "v24@0:8@16"
  imp = 0x0000000100000d80 (KCObjc`-[LGPerson setNickName:])
}
(lldb) p $1.get(8)
(method_t) $10 = {
  name = "nickName"
  types = 0x0000000100000f8e "@16@0:8"
  imp = 0x0000000100000d60 (KCObjc`-[LGPerson nickName])
}
(lldb) p $1.get(9)
Assertion failed: (i < count), function get, file /Users/cloud/Documents/iOS/0921/20200921--大師班第8節(jié)課--消息流程/20200921-大師班第8天-方法查找流程/01--課堂代碼/001-objc_msgSend分析探索/runtime/objc-runtime-new.h, line 438.
error: Execution was interrupted, reason: signal SIGABRT.
The process has been returned to the state before expression evaluation.

執(zhí)行完int methodListIsFixedUp = mlist->isFixedUp()查看mlist中的方法是否排序,還是和之前一樣。

(lldb) p mlist
(const method_list_t *) $11 = 0x00000001000020c8
(lldb) p *$0
(const method_list_t) $12 = {
  entsize_list_tt<method_t, method_list_t, 3> = {
    entsizeAndFlags = 26
    count = 9
    first = {
      name = "sayHello"
      types = 0x0000000100000f86 "v16@0:8"
      imp = 0x0000000100000c40 (KCObjc`-[LGPerson sayHello])
    }
  }
}
(lldb) p $12.get(0)
(method_t) $13 = {
  name = "sayHello"
  types = 0x0000000100000f86 "v16@0:8"
  imp = 0x0000000100000c40 (KCObjc`-[LGPerson sayHello])
}
(lldb) p $12.get(1)
(method_t) $14 = {
  name = "say666"
  types = 0x0000000100000f86 "v16@0:8"
  imp = 0x0000000100000cd0 (KCObjc`-[LGPerson say666])
}
(lldb) p $12.get(2)
(method_t) $15 = {
  name = "sayNB"
  types = 0x0000000100000f86 "v16@0:8"
  imp = 0x0000000100000c70 (KCObjc`-[LGPerson sayNB])
}
(lldb) p $12.get(3)
(method_t) $16 = {
  name = "sayMaster"
  types = 0x0000000100000f86 "v16@0:8"
  imp = 0x0000000100000ca0 (KCObjc`-[LGPerson sayMaster])
}
(lldb) p $12.get(4)
(method_t) $17 = {
  name = "lgName"
  types = 0x0000000100000f8e "@16@0:8"
  imp = 0x0000000100000d00 (KCObjc`-[LGPerson lgName])
}
(lldb) p $12.get(5)
(method_t) $18 = {
  name = "setLgName:"
  types = 0x0000000100000f96 "v24@0:8@16"
  imp = 0x0000000100000d30 (KCObjc`-[LGPerson setLgName:])
}
(lldb) p $12.get(6)
(method_t) $19 = {
  name = ".cxx_destruct"
  types = 0x0000000100000f86 "v16@0:8"
  imp = 0x0000000100000db0 (KCObjc`-[LGPerson .cxx_destruct])
}
(lldb) p $12.get(7)
(method_t) $20 = {
  name = "setNickName:"
  types = 0x0000000100000f96 "v24@0:8@16"
  imp = 0x0000000100000d80 (KCObjc`-[LGPerson setNickName:])
}
(lldb) p $12.get(8)
(method_t) $21 = {
  name = "nickName"
  types = 0x0000000100000f8e "@16@0:8"
  imp = 0x0000000100000d60 (KCObjc`-[LGPerson nickName])
}
(lldb) p $12.get(9)
Assertion failed: (i < count), function get, file /Users/cloud/Documents/iOS/0921/20200921--大師班第8節(jié)課--消息流程/20200921-大師班第8天-方法查找流程/01--課堂代碼/001-objc_msgSend分析探索/runtime/objc-runtime-new.h, line 438.
error: Execution was interrupted, reason: signal SIGABRT.
The process has been returned to the state before expression evaluation.
方法的二分查找流程.png

本類中沒有疯兼,從父類的緩存中查找

從父類中查找遞歸

找到返回Imp并將Imp填充緩存log_and_fill_cache(cls, imp, sel, inst, curClass);方便下次快速查找幕与,沒找到則跳入動態(tài)方法決議,系統(tǒng)給一個挽救的機會,實現[cls resolveInstanceMethod:sel]方法镇防,

    if (slowpath(behavior & LOOKUP_RESOLVER)) {
        behavior ^= LOOKUP_RESOLVER;
        return resolveMethod_locked(inst, sel, cls, behavior);
    }

若都沒找到啦鸣,return imp == forward_imp

void *_objc_forward_handler = nil;
void *_objc_forward_stret_handler = nil;

#else

// Default forward handler halts the process.
__attribute__((noreturn, cold)) void
objc_defaultForwardHandler(id self, SEL sel)
{
    _objc_fatal("%c[%s %s]: unrecognized selector sent to instance %p "
                "(no message forward handler is installed)", 
                class_isMetaClass(object_getClass(self)) ? '+' : '-', 
                object_getClassName(self), sel_getName(sel), self);
}
void *_objc_forward_handler = (void*)objc_defaultForwardHandler;

將say666對象方法注釋掉,報錯如下
//- (void)say666{
//    NSLog(@"%s",__func__);
//}

2020-11-02 02:48:07.732479+0800 KCObjc[26239:1214027] -[LGPerson sayHello]
2020-11-02 02:48:07.733236+0800 KCObjc[26239:1214027] -[LGPerson say666]: unrecognized selector sent to instance 0x100725e30
2020-11-02 02:48:07.735713+0800 KCObjc[26239:1214027] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[LGPerson say666]: unrecognized selector sent to instance 0x100725e30'
*** First throw call stack:
(
    0   CoreFoundation                      0x00007fff31e89b57 __exceptionPreprocess + 250
    1   libobjc.A.dylib                     0x00000001002d15ba objc_exception_throw + 42
    2   CoreFoundation                      0x00007fff31f08be7 -[NSObject(NSObject) __retain_OA] + 0
    3   CoreFoundation                      0x00007fff31dee3bb ___forwarding___ + 1427
    4   CoreFoundation                      0x00007fff31dedd98 _CF_forwarding_prep_0 + 120
    5   KCObjc                              0x0000000100000c61 main + 81
    6   libdyld.dylib                       0x00007fff6be78cc9 start + 1
)
libc++abi.dylib: terminating with uncaught exception of type NSException

不存在所謂的“+”和“-”方法来氧,底層都為函數

動態(tài)方法決議

一直沒有找到方法的Imp,在報錯之前诫给,系統(tǒng)給一次挽救的機會,在LGPerson中是否實現了類方法+ (BOOL)resolveInstanceMethod:(SEL)sel啦扬,SEL resolve_sel = @selector(resolveInstanceMethod:);,在LGPerson的元類中找實例方法!lookUpImpOrNil(cls, resolve_sel, cls->ISA()),如果存在中狂,則重新進行慢速查找一遍,看類中是否存在say666方法扑毡,存在即返回胃榕,不存在就執(zhí)行報錯的forward_imp

    // No implementation found. Try method resolver once.

    if (slowpath(behavior & LOOKUP_RESOLVER)) {
        behavior ^= LOOKUP_RESOLVER;
        return resolveMethod_locked(inst, sel, cls, behavior);
    }
    
static NEVER_INLINE IMP
resolveMethod_locked(id inst, SEL sel, Class cls, int behavior)
{
    runtimeLock.assertLocked();
    ASSERT(cls->isRealized());

    runtimeLock.unlock();

    if (! cls->isMetaClass()) {
        // try [cls resolveInstanceMethod:sel]
        resolveInstanceMethod(inst, sel, cls);
    } 
    else {
        // try [nonMetaClass resolveClassMethod:sel]
        // and [cls resolveInstanceMethod:sel]
        resolveClassMethod(inst, sel, cls);
        if (!lookUpImpOrNil(inst, sel, cls)) {
            resolveInstanceMethod(inst, sel, cls);
        }
    }

    // chances are that calling the resolver have populated the cache
    // so attempt using it
    return lookUpImpOrForward(inst, sel, cls, behavior | LOOKUP_CACHE);
}
static void resolveInstanceMethod(id inst, SEL sel, Class cls)
{
    runtimeLock.assertUnlocked();
    ASSERT(cls->isRealized());
    SEL resolve_sel = @selector(resolveInstanceMethod:);

    if (!lookUpImpOrNil(cls, resolve_sel, cls->ISA())) {
        // Resolver not implemented.
        return;
    }

    BOOL (*msg)(Class, SEL, SEL) = (typeof(msg))objc_msgSend;
    bool resolved = msg(cls, resolve_sel, sel);

    // Cache the result (good or bad) so the resolver doesn't fire next time.
    // +resolveInstanceMethod adds to self a.k.a. cls
    IMP imp = lookUpImpOrNil(inst, sel, cls);

    if (resolved  &&  PrintResolving) {
        if (imp) {
            _objc_inform("RESOLVE: method %c[%s %s] "
                         "dynamically resolved to %p", 
                         cls->isMetaClass() ? '+' : '-', 
                         cls->nameForLogging(), sel_getName(sel), imp);
        }
        else {
            // Method resolver didn't add anything?
            _objc_inform("RESOLVE: +[%s resolveInstanceMethod:%s] returned YES"
                         ", but no new implementation of %c[%s %s] was found",
                         cls->nameForLogging(), sel_getName(sel), 
                         cls->isMetaClass() ? '+' : '-', 
                         cls->nameForLogging(), sel_getName(sel));
        }
    }
}

+ (BOOL)resolveInstanceMethod:(SEL)sel{
    
    if (sel == @selector(say666)) {
        NSLog(@"%@ 來了哦",NSStringFromSelector(sel));
        
        IMP imp           = class_getMethodImplementation(self, @selector(sayMaster));
        Method sayMMethod = class_getInstanceMethod(self, @selector(sayMaster));
        const char *type  = method_getTypeEncoding(sayMMethod);
        return class_addMethod(self, sel, imp, type);
    }
    
    return [super resolveInstanceMethod:sel];
}

//輸出
2020-11-03 01:10:58.078990+0800 KCObjc[527:426803] -[LGPerson sayHello]
2020-11-03 01:10:58.079698+0800 KCObjc[527:426803] say666 來了哦
2020-11-03 01:10:58.079928+0800 KCObjc[527:426803] -[LGPerson sayMaster]
動態(tài)方法決議@2x.png

LGPerson分類中存在同名的sayHell0方法,則二分查找流程如下

方法的二分查找分類中有同名的方法.png

分類同名方法.png

main@2x.png
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
  • 序言:七十年代末瞄摊,一起剝皮案震驚了整個濱河市勋又,隨后出現的幾起案子,更是在濱河造成了極大的恐慌换帜,老刑警劉巖楔壤,帶你破解...
    沈念sama閱讀 216,591評論 6 501
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現場離奇詭異惯驼,居然都是意外死亡蹲嚣,警方通過查閱死者的電腦和手機递瑰,發(fā)現死者居然都...
    沈念sama閱讀 92,448評論 3 392
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來隙畜,“玉大人抖部,你說我怎么就攤上這事∫槎瑁” “怎么了您朽?”我有些...
    開封第一講書人閱讀 162,823評論 0 353
  • 文/不壞的土叔 我叫張陵,是天一觀的道長换淆。 經常有香客問我,道長几颜,這世上最難降的妖魔是什么倍试? 我笑而不...
    開封第一講書人閱讀 58,204評論 1 292
  • 正文 為了忘掉前任,我火速辦了婚禮蛋哭,結果婚禮上县习,老公的妹妹穿的比我還像新娘。我一直安慰自己谆趾,他們只是感情好躁愿,可當我...
    茶點故事閱讀 67,228評論 6 388
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著沪蓬,像睡著了一般彤钟。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上跷叉,一...
    開封第一講書人閱讀 51,190評論 1 299
  • 那天逸雹,我揣著相機與錄音,去河邊找鬼云挟。 笑死梆砸,一個胖子當著我的面吹牛,可吹牛的內容都是我干的园欣。 我是一名探鬼主播帖世,決...
    沈念sama閱讀 40,078評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼沸枯!你這毒婦竟也來了日矫?” 一聲冷哼從身側響起,我...
    開封第一講書人閱讀 38,923評論 0 274
  • 序言:老撾萬榮一對情侶失蹤绑榴,失蹤者是張志新(化名)和其女友劉穎搬男,沒想到半個月后,有當地人在樹林里發(fā)現了一具尸體彭沼,經...
    沈念sama閱讀 45,334評論 1 310
  • 正文 獨居荒郊野嶺守林人離奇死亡缔逛,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 37,550評論 2 333
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現自己被綠了。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片褐奴。...
    茶點故事閱讀 39,727評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡按脚,死狀恐怖,靈堂內的尸體忽然破棺而出敦冬,到底是詐尸還是另有隱情辅搬,我是刑警寧澤,帶...
    沈念sama閱讀 35,428評論 5 343
  • 正文 年R本政府宣布脖旱,位于F島的核電站堪遂,受9級特大地震影響,放射性物質發(fā)生泄漏萌庆。R本人自食惡果不足惜溶褪,卻給世界環(huán)境...
    茶點故事閱讀 41,022評論 3 326
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望践险。 院中可真熱鬧猿妈,春花似錦、人聲如沸巍虫。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,672評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽占遥。三九已至俯抖,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間瓦胎,已是汗流浹背蚌成。 一陣腳步聲響...
    開封第一講書人閱讀 32,826評論 1 269
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留凛捏,地道東北人担忧。 一個月前我還...
    沈念sama閱讀 47,734評論 2 368
  • 正文 我出身青樓,卻偏偏與公主長得像坯癣,于是被迫代替她去往敵國和親瓶盛。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 44,619評論 2 354

推薦閱讀更多精彩內容