iOS-底层原理09-msgSend消息查找流程&动态方法决议

《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节课--消息流程/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.

执行完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节课--消息流程/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);方便下次快速查找,没找到则跳入动态方法决议,系统给一个挽救的机会,实现[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

不存在所谓的“+”和“-”方法,底层都为函数

动态方法决议

一直没有找到方法的Imp,在报错之前,系统给以次挽救的机会,在LGPerson中是否实现了类方法+ (BOOL)resolveInstanceMethod:(SEL)sel,SEL resolve_sel = @selector(resolveInstanceMethod:);,在LGPerson的元类中找实例方法!lookUpImpOrNil(cls, resolve_sel, cls->ISA()),如果存在,则重新进行慢速查找一遍,看类中是否存在say666方法,存在即返回,不存在就执行报错的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]
动态方法决议@2x.png

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

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

分类同名方法.png

main@2x.png

推荐阅读更多精彩内容