iOS开发之Runtime-消息转发

在Objective-C中调用方法,其实是调用objc_msgSend()函数。

  1. 这个函数会先进行快速查找,也就是从方法缓存中查找,并且这个快速查找过程是直接由汇编实现的;
  2. 如果没有缓存,会进入慢速查找流程lookUpImpOrForward(),从类的方法列表objc_class->bit.data()(rw)->ro->baseMethodList中去查找,同时,被调用过的方法还会以Hash表的结构保存在objc_class->cache中,我们叫他慢速查找;
  3. 如果第2步中也没有找到,继续沿着继承链从父类中查找,也是先找缓存,再找方法列表;
  4. 上述任何一步中如果找到了IMP,就会把他缓存下来(缓存到当前类)。如果最终都没有IMP,则进入消息转发流程。


    lookUpImpOrForward.png

一、动态方法解析:resolveMethod

当没有查找到 SEL 对应的 IMP 时,系统会调用相关类的 +(BOOL)resolveInstanceMethod:(SEL)sel
+(BOOL)resolveClassMethod:(SEL)sel 来允许我们为 SEL 指定一个 IMP。

#include <objc/runtime.h>


@implementation Dog

//- (void)walk {
//    NSLog(@"walk");
//}

- (void)run {
    NSLog(@"run");
}

+ (BOOL)resolveInstanceMethod:(SEL)sel {
    
    if (sel == @selector(walk)) {
        NSLog(@"Call walk");
        Method method = class_getInstanceMethod(self, @selector(run));
        IMP imp = method_getImplementation(method);
        const char *types = method_getTypeEncoding(method);
        class_addMethod(self, sel, imp, types);
        return YES;
    }
    
    return [super resolveInstanceMethod:sel];
}

运行 [dog walk],控制台输出

2020-04-02 16:28:54.656555+0800 tset[88242:1804683] Call walk
2020-04-02 16:28:54.657590+0800 tset[88242:1804683] run

如果没有对上面两个方法做处理,则会进入下面。

二、消息的快速转发

- (id)forwardingTargetForSelector:(SEL)aSelector,我们可以在这个方法指定一个target来处理aSelector

- (id)forwardingTargetForSelector:(SEL)aSelector {
    NSLog(@"will forward msg: %s", (char *)aSelector);
    Cat *cat = [[Cat alloc] init];
    if ([cat respondsToSelector:aSelector]) {
        NSLog(@"forwards msg %s success!", (char *)aSelector);
        return cat;
    }
    return [super forwardingTargetForSelector:aSelector];
}

运行 [dog walk],控制台输出

2020-04-02 16:55:16.636043+0800 tset[89075:1816360] will forward msg: walk
2020-04-02 16:55:16.636884+0800 tset[89075:1816360] forwards msg walk success!
2020-04-02 16:55:16.637107+0800 tset[89075:1816360] -[Cat walk]

三、消息的慢速转发

如果我们没有实现上面的方法,则会调用新的方法.

1、方法签名

- (NSMethodSignature *)methodSignatureForSelector:(SEL)aSelector {
    NSLog(@"method signature for msg: %s", (char *)aSelector);
    if (aSelector == @selector(anwser)) {
        NSLog(@"method signature for msg: %s susscess!", (char *)aSelector);
        return [NSMethodSignature signatureWithObjCTypes:"v@:"];
    }
    return [super methodSignatureForSelector:aSelector];
}

2、事务的转发

- (void)forwardInvocation:(NSInvocation *)anInvocation {
    NSLog(@"forwardInvocation: %s", (char *)anInvocation.selector);
    SEL selector = [anInvocation selector];
    Cat *cat = [[Cat alloc] init];
    if ([cat respondsToSelector:selector]) {
        NSLog(@"give invacation a target");
        [anInvocation invokeWithTarget:cat];
    } else {
        [super forwardInvocation:anInvocation];
    }
}

四、总结

当方法查找流程结束后仍没有找到 IMP,runtime 首先进行 动态方法解析,之后再进入快速的消息转发,最后慢速消息转发:

  1. 动态方法解析:调用 +resolveInstanceMethod 或 +resolveClassMethod 尝试获取 IMP
  2. 没有 IMP,进入快速消息转发,调用 -forwardingTargetForSelector: 尝试获取一个可以处理的对象
  3. 仍没有处理,进入慢速转发,调用 -methodSignatureForSelector: 获取到方法签名后,将消息封装为一个invocation 再调用 -forwardInvocation: 进行处理。
    可见,当一个方法没有实现时,runtime 给了3次机会让我们进行处理。
    下面是动态方法解析和消息转发的流程:


    u=2316952610,196017428&fm=15&gp=0.jpg

五、源码

下面附录一份在objc4-750中lookUpImpOrForward的源码,这个方法在objc-runtime-new.mm类中。这个方法实现了慢速查找到动态转发的整个过程。

  1. 查找准备 #16#51
    #40行代码:realizeClass(cls),这个函数把当前类的实现加载到内存中,它会沿着继承链递归调用,一直加载到NSObject,包括元类以及元类的继承链中的类,主要加载的是类的方法列表,实现的协议方法,属性方法,以及分类方法,来保证接下来的方法查找
    #45_class_initialize (_class_getNonMetaClass(cls, inst))
    NSObject类中定义了两个类方法 + load,和 + initialize,这个方法就是从当前类开始沿着继承链对每个类调用 + initialize 方法。
  2. 在当前类中查找方法#57#70
  3. 顺着继承链在父类中查找 #72#108
    当在父类中找了IMP,会把IMP存到当前类的缓存中,而不是父类。
  4. 动态方法解析 #110#126
/***********************************************************************
* lookUpImpOrForward.
* The standard IMP lookup. 
* initialize==NO tries to avoid +initialize (but sometimes fails)
* cache==NO skips optimistic unlocked lookup (but uses cache elsewhere)
* Most callers should use initialize==YES and cache==YES.
* inst is an instance of cls or a subclass thereof, or nil if none is known. 
*   If cls is an un-initialized metaclass then a non-nil inst is faster.
* May return _objc_msgForward_impcache. IMPs destined for external use 
*   must be converted to _objc_msgForward or _objc_msgForward_stret.
*   If you don't want forwarding at all, use lookUpImpOrNil() instead.
**********************************************************************/
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 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();
    checkIsKnownClass(cls);

    if (!cls->isRealized()) {
        realizeClass(cls);
    }

    if (initialize  &&  !cls->isInitialized()) {
        runtimeLock.unlock();
        _class_initialize (_class_getNonMetaClass(cls, inst));
        runtimeLock.lock();
        // 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
    }

    
 retry:    
    runtimeLock.assertLocked();

    // 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.
    {
        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 {
                    // Found a forward:: entry in a superclass.
                    // Stop searching, but don't cache yet; call method 
                    // resolver for this class first.
                    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.unlock();
        _class_resolveMethod(cls, sel, inst);
        runtimeLock.lock();
        // 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.

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

 done:
    runtimeLock.unlock();

    return imp;
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 218,204评论 6 506
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 93,091评论 3 395
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 164,548评论 0 354
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,657评论 1 293
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,689评论 6 392
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,554评论 1 305
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,302评论 3 418
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,216评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,661评论 1 314
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,851评论 3 336
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,977评论 1 348
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,697评论 5 347
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,306评论 3 330
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,898评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 33,019评论 1 270
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 48,138评论 3 370
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,927评论 2 355

推荐阅读更多精彩内容