美文网首页
九、消息流程之动态决议

九、消息流程之动态决议

作者: Mlqq | 来源:发表于2021-04-07 10:27 被阅读0次

    在消息经过慢速查找之后还没有找到,就会走到resolveMethod_locked进行消息动态决议,看一下resolveMethod_locked方法的实现:

    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 (!lookUpImpOrNilTryCache(inst, sel, cls)) {
                resolveInstanceMethod(inst, sel, cls);
            }
        }
    
        // chances are that calling the resolver have populated the cache
        // so attempt using it
        return lookUpImpOrForwardTryCache(inst, sel, cls, behavior);
    
    }
    

    这个方法可以看出实例方法和类方法的动态决议流程不一样,分别看一下。

    1、实例方法的动态决议

    实例方法动态决议调用的是resolveInstanceMethod方法:

    static void resolveInstanceMethod(id inst, SEL sel, Class cls)
    {
        runtimeLock.assertUnlocked();
        ASSERT(cls->isRealized());
        SEL resolve_sel = @selector(resolveInstanceMethod:);
    
        if (!lookUpImpOrNilTryCache(cls, resolve_sel, cls->ISA(/*authenticated*/true))) {
            // 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 = lookUpImpOrNilTryCache(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));
            }
        }
    }
    

    resolveInstanceMethod:是一个类方法,需要在元类里面查找有没有实现,如果没有实现就直接返回了。如果实现了向这个方法发送一个消息调用这个方法进行处理

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

    2、类方法的动态决议

    类方法的动态决议调用的是resolveClassMethod方法:

    static void resolveClassMethod(id inst, SEL sel, Class cls)
    {
        runtimeLock.assertUnlocked();
        ASSERT(cls->isRealized());
        ASSERT(cls->isMetaClass());
    
        if (!lookUpImpOrNilTryCache(inst, @selector(resolveClassMethod:), cls)) {
            // Resolver not implemented.
            return;
        }
    
        Class nonmeta;
        {
            mutex_locker_t lock(runtimeLock);
            nonmeta = getMaybeUnrealizedNonMetaClass(cls, inst);
            // +initialize path should have realized nonmeta already
            if (!nonmeta->isRealized()) {
                _objc_fatal("nonmeta class %s (%p) unexpectedly not realized",
                            nonmeta->nameForLogging(), nonmeta);
            }
        }
        BOOL (*msg)(Class, SEL, SEL) = (typeof(msg))objc_msgSend;
        bool resolved = msg(nonmeta, @selector(resolveClassMethod:), sel);
    
        // Cache the result (good or bad) so the resolver doesn't fire next time.
        // +resolveClassMethod adds to self->ISA() a.k.a. cls
        IMP imp = lookUpImpOrNilTryCache(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 resolveClassMethod:%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));
            }
        }
    }
    

    需要注意的是参数cls是元类。其他的跟实例方法动态决议一样,先判断元类里面实现resolveClassMethod这个方法没有,如果没实现就是直接返回了。如果实现了就向这个方法发送一个消息:

    BOOL (*msg)(Class, SEL, SEL) = (typeof(msg))objc_msgSend;
    bool resolved = msg(nonmeta, @selector(resolveClassMethod:), sel);
    

    3、消息动态决议的实用

    知道了消息的流程最重要的就是要用它解决问题方法找不到导致的闪退。先做一下准备工作:

    image.png

    在MlqqObject这里类里面定义了两个实例方法:messageResolutionInstancMethodHasNOIMPmessageResolutionInstancMethodHasIMP,其中messageResolutionInstancMethodHasNOIMP没有实现,messageResolutionInstancMethodHasIMP有实现,两个类方法:messageResolutionClassMethodHasNOIMPmessageResolutionClassMethodHasIMP,其中messageResolutionClassMethodHasNOIMP没有实现,messageResolutionClassMethodHasIMP有实现。我们现在main函数里面调没哟实现的实例方法messageResolutionInstancMethodHasNOIMP,肯定会闪退:

    image.png

    3.1 实例方法动态决议实用

    既然messageResolutionClassMethodHasNOIMP没有实现,可以通过resolveInstanceMethod这个方法修改其实现的IMP,你来调这个就可以了,请不要闪退:

    + (BOOL)resolveInstanceMethod:(SEL)sel {
        NSLog(@"%@ 来了",NSStringFromSelector(sel));
        if(sel == @selector(messageResolutionInstancMethodHasNOIMP)) {
            //获取到已经实现方法的IMP
            IMP imp = class_getMethodImplementation(self, @selector(messageResolutionInstancMethodHasIMP));
            //获取已经实现的方法IMP的编码
            Method method = class_getInstanceMethod(self, @selector(messageResolutionInstancMethodHasIMP));
            const char * type = method_getTypeEncoding(method);
            //将sel的IMP修改为messageResolutionInstancMethodHasIMP的IMP
            return class_addMethod(self, sel, imp, type);
        }
        
        return [super resolveInstanceMethod:sel];
    }
    

    通过上面的修改当调messageResolutionInstancMethodHasNOIMP这个没实现的方法时,就会调到messageResolutionInstancMethodHasIMP这个已经实现的方法,起码不会闪退了

    image.png

    3.2 类方法方法动态决议实用

    同理实现resolveClassMethod可以解决类方法没有实现导致的闪退:

    + (BOOL)resolveClassMethod:(SEL)sel {
        
        NSLog(@"%@ 来了",NSStringFromSelector(sel));
        if(sel == @selector(messageResolutionClassMethodHasNOIMP)) {
             //获取到已经实现方法的IMP
            IMP imp = class_getMethodImplementation(objc_getMetaClass("MlqqObject"), @selector(messageResolutionClassMethodHasIMP));
            //获取已经实现的方法IMP的编码
            Method method = class_getInstanceMethod(objc_getMetaClass("MlqqObject"), @selector(messageResolutionClassMethodHasIMP));
            const char * type = method_getTypeEncoding(method);
            //将sel的IMP修改为messageResolutionClassMethodHasIMP的IMP
            return class_addMethod(objc_getMetaClass("MlqqObject"), sel, imp, type);
        }
        
        return [super resolveClassMethod:sel];
    }
    

    这里需要注意的是类方法是存在元类里的,所以操作这里的class都必须为元类:

    image.png

    3.3 消息动态决议的高级应用

    再来看一下resolveMethod_locked这个方法:

    image.png

    不知道大家有没有注意到这两行代码,这里为什么还要在去调一下实例方法的动态决议呢?答案就在下面这张图里:

    image.png

    这个方法的参数cls是元类,lookUpImpOrNilTryCache方法会在当前类找sel的实现如果没有找到,会向父类去找,直到父类为nil,根据这张图显示根元类的父类是NSObject类。也就是说如果是类方法没有实现,系统会先调resolveClassMethod去决议一次,如果在resolveClassMethod已经处理了,lookUpImpOrNilTryCache这个方法的值为tureif条件不满足,如果resolveClassMethod没有处理,lookUpImpOrNilTryCache这个方法的值为fale,再调resolveInstanceMethod(inst, sel, cls);看看根类能不能解决。

    知道这个流程之后,我们不在类里面实现resolveClassMethod这个方法来解决类方法找不到导致闪退,而是实现NSObjectresolveInstanceMethod,这样我们就可以同时解决实例方法和类方法没实现导致的闪退了。我们可以创建一个NSObject的分类,然后重写一下resolveInstanceMethod这个方法:

    image.png

    相关文章

      网友评论

          本文标题:九、消息流程之动态决议

          本文链接:https://www.haomeiwen.com/subject/uhzykltx.html