美文网首页GitHub 中文社区
runtime源码解析(二) 方法调用

runtime源码解析(二) 方法调用

作者: Jack_deng | 来源:发表于2017-07-18 20:30 被阅读0次

    写在前面

    前面说了Runtime源码解析(一) 方法加载。既然方法都加载好了,那么现在就来说说方法调用。大家基本上都知道[receiver message]会被翻译为 objc_msgSend(receiver, @selector(message))。不过在说这个前想先说说+initialize方法。为什么要先说它呢?因为在类或它的子类收到第一条消息之前会调用initialize方法,这里所指的消息包括实例方法和类方法的调用。而且这个方法是以懒加载的方式被调用的。

    +initialize

    initialize的调用栈:_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就是调用了lookUpImpOrForward。下面主要说说这个方法

    // 这个方法非常关键,就是查找方法的,返回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()) {  // 现在这里时候,这个代码块不会走的,因为方法加载的时候已经isRealized过了
            runtimeLock.unlockRead();
            runtimeLock.write();
            realizeClass(cls);
            runtimeLock.unlockWrite();
            runtimeLock.read();
        }
        if (initialize  &&  !cls->isInitialized()) {
            runtimeLock.unlockRead();
            _class_initialize (_class_getNonMetaClass(cls, inst));  // 这里就是initialize方法,第一次发送方法前会走这个代码块
            runtimeLock.read();
        }    
     retry:    
        runtimeLock.assertReading();
        imp = cache_getImp(cls, sel);
        if (imp) goto done;
        {
            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.
        {
            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 动态方法解析
            _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 消息转发
        imp = (IMP)_objc_msgForward_impcache;
        cache_fill(cls, sel, imp, inst);
     done:
        runtimeLock.unlockRead();
        return imp;
    }
    

    lookUpImpOrForward是个是很重要的方法,里面还有的方法我就不展开说了,下面开始说说消息转发流程。(如果在正常的方法列表里没有查找到方法,就进入消息转发流程)

    消息转发

    首先是动态方法解析,_class_resolveMethod里面又调用了_class_resolveInstanceMethod

    static void _class_resolveInstanceMethod(Class cls, SEL sel, id inst)
    {
        // 查找类是否实现了+ (BOOL)resolveInstanceMethod:(SEL)sel方法
        // 如果没有实现就直接返回
        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
      // 调用类里面实现的+ (BOOL)resolveInstanceMethod:(SEL)sel
        IMP imp = lookUpImpOrNil(cls, sel, inst, 
                                 NO/*initialize*/, YES/*cache*/, NO/*resolver*/);
    }
    

    总结

    最后汇总一下正常方法调用的过程,总的来看还是很合情合理的:

    • 查找当前类的缓存和方法列表
    • 查找父类的缓存和方法列表
    • 动态方法解析
    • 消息转发

    相关文章

      网友评论

        本文标题:runtime源码解析(二) 方法调用

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