OC消息转发

从 OC 转发机制说起

在 OC 中,方法调用也被称为发送消息,向一个
的方法进行调用的时候,其实底层都会转换成 objc_msgSend 方法来进行.

[XXObject hello]会转换成objc_msgSend(XXObject,@selector(hello))

通过 objc_msgSend 来进行寻找方法,缓存并且调用方法等一系列的过程。

如果你发送的消息的实现不存在,并不会立即 Crash,反而有几个机会可以弥补,这个就是 Runtime 的消息转发。其过程由一下几步组成

  1. 如果是类方法不存在则会调用 resolveClassMethod:,如果是一个实例方法,那么会调用 resolveInstanceMethod:方法,这个时候可以将实现动态的添加到相应的类中,并且返回 YES, 如果返回 NO 则会进入到下一步。
  2. 此时forwardingTargetForSelector: 将会被调用, 你可以在这个方法寻找一个合适的执行者,并向这个 target 转发消息。
  3. 如果前 2 步都是失败的那么methodSignatureForSelector:会被调用。你可以在此方法生成方法签名,为下一步做准备
  4. 之后来到 forwardInvocation 方法来进行最终的方法调用,你可以指向其他类来 invoke 这个 Invocation 已达到转发执行的目的。
  5. 当所有方法都失败,最后只能走到终点 doesNotRecognizeSelector:会被调用,在控制台打出 unrecognized selector sent to instance xxxx等消息。

从源码看消息转发

objc_msgSend

因为 objc_msgSend 是汇编实现的所以提到 objc_msgSend 都会以如下伪代码来描述

id objc_msgSend(id self, SEL _cmd, ...) {
  Class class = object_getClass(self);
  IMP imp = class_getMethodImplementation(class, _cmd);
  return imp ? imp(self, _cmd, ...) : 0;
}

在汇编片段中有一段是这么描述的

.macro MethodTableLookup

    MESSENGER_END_SLOW
    
    SaveRegisters

    // _class_lookupMethodAndLoadCache3(receiver, selector, class)

    movq    $0, %a1
    movq    $1, %a2
    movq    %r11, %a3
    call    __class_lookupMethodAndLoadCache3

    // IMP is now in %rax
    movq    %rax, %r11

    RestoreRegisters

.endmacro

表示在缓存中没找到方法实现的时候,会调用__class_lookupMethodAndLoadCache3函数,那么这个方法做了什么呢,让我们一起看看。

IMP _class_lookupMethodAndLoadCache3(id obj, SEL sel, Class cls)
{
    return lookUpImpOrForward(cls, sel, obj, 
                              YES/*initialize*/, NO/*cache*/, YES/*resolver*/);
}

看来只是简单的调用 lookUpImpOrForward方法,这边有2个参数需要注意一下,首先 initialize 这个参数在 lookUpImpOrForward方法的注释中有提到

  • initialize==NO tries to avoid +initialize (but sometimes fails)

表示如果是 NO 的话,那么不会去调用类方法+initialize,因为我们的入口是缓存没命中的情况下,也是需要判断这个类是不是第一次收到消息,所以这里设置成了 YES ,表示需要调用+initialize
而 cache 参数呢,在注释中这么说

cache==NO skips optimistic unlocked lookup (but uses cache elsewhere)

设置 NO 的话会不先去找 cache ,因为进来这个方法之前已经找过了

话不多说,我们进入 lookUpImpOrForward 方法。(全部代码在文末贴出)

此方法比较长,我们一步步来分析。

runtimeLock.assertUnlocked();

首先在 debug 模式下加锁。

if (cache) {
        imp = cache_getImp(cls, sel);
        if (imp) return imp;
    }

因为我们cache 为 NO,所以这里将会跳过。

   //没有实现类就去实现类
    if (!cls->isRealized()) {
        rwlock_writer_t lock(runtimeLock);
        realizeClass(cls);
    }

先判断类有没有被实现,如果没有,则去实现

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

判断 class 有没有被 initialize ,如果没用,则调用 _class_initialize 来进行类的 initialize ,从 _class_initialize 方法内部我们看到,initialize 的调用时机是从子类到父类的。

    runtimeLock.read();

之后进入到这,因为我们执行到这,可能 category 会添加方法,所以这里加锁进行原子操作。

    // Try this class's cache.

    imp = cache_getImp(cls, sel);
    if (imp) goto done;

首先进入查找的第一步,现在类的缓存中寻找 方法实现。cache_getImp 也是由汇编实现。

    // Try this class's method lists.

    meth = getMethodNoSuper_nolock(cls, sel);
    if (meth) {
        log_and_fill_cache(cls, meth->imp, sel, inst, cls);
        imp = meth->imp;
        goto done;
    }

查找失败的时候,会在类的方法列表中寻找,找到则加入 cache 。如果没找到,进入下一步。此方法有对方法查找过程优化,会对已经排序的方法进行2分查找,对未排序的进行线性查找。

curClass = cls;
    while ((curClass = curClass->superclass)) {
        // 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;
            }
        }

本类找不到,将会去父类缓存中查找。如果找到,并且把它加入父类的缓存。如果找不到,则会去父类的方法列表中寻找,和上面的方法是一样的。

 // No implementation found. Try method resolver once.

    if (resolver  &&  !triedResolver) {
        runtimeLock.unlockRead();
        _class_resolveMethod(cls, sel, inst);
        // 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;
    }

当所有的步骤都找不到,则会进入_class_resolveMethod函数,类对象一个添加方法实现的机会,以下是这个方法的实现

void _class_resolveMethod(Class cls, SEL sel, id inst)
{
    if (! cls->isMetaClass()) {
        // try [cls resolveInstanceMethod:sel]
        _class_resolveInstanceMethod(cls, sel, inst);
    } 
    else {
        // try [nonMetaClass resolveClassMethod:sel]
        // and [cls resolveInstanceMethod:sel]
        _class_resolveClassMethod(cls, sel, inst);
        if (!lookUpImpOrNil(cls, sel, inst, 
                            NO/*initialize*/, YES/*cache*/, NO/*resolver*/)) 
        {
            _class_resolveInstanceMethod(cls, sel, inst);
        }
    }
}

没错,此方法会调用对象resolveInstanceMethod(如果是类方法会调用 resolveClassMethod),这这个方法,你可以动态添加一个方法实现。也是消息转发的第一步。

回到上一步,如果 resolveInstanceMethod 返回 YES,也就是动态添加了方法的实现,这个会 goto retry,重新走一边查找过程,并且不会第二次执行 _class_resolveMethod,因为 triedResolver 已经设置成 YES。

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

所有的方法都没找到方法的实现之后,无奈只能将 _objc_msgForward_impcache 指针方法,表示未找到方法实现,准备下一步的消息转发流程。

关于转发之后的流程并没有在 Runtime 中实现,而是在 CF 层中实现,如果想了解 CF 中做了哪些事,已经如何一步步调用后续方法可以看杨萧玉的这篇文章http://yulingtianxia.com/blog/2016/06/15/Objective-C-Message-Sending-and-Forwarding 介绍的很详细,值得一读。

实现代码

IMP lookUpImpOrForward(Class cls, SEL sel, id inst, 
                       bool initialize, bool cache, bool resolver)
{
    Class curClass;
    IMP imp = nil;
    Method meth;
    bool triedResolver = NO;

    runtimeLock.assertUnlocked();

    // Optimistic cache lookup
    //找不到缓存继续
    if (cache) {
        imp = cache_getImp(cls, sel);
        if (imp) return imp;
    }

    //没有实现类就去实现类
    if (!cls->isRealized()) {
        rwlock_writer_t lock(runtimeLock);
        realizeClass(cls);
    }
    
    
    if (initialize  &&  !cls->isInitialized()) {
        _class_initialize (_class_getNonMetaClass(cls, inst));
        // 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
    }

    // The lock is held 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.
 retry:
    runtimeLock.read();

    // Ignore GC selectors
    if (ignoreSelector(sel)) {
        imp = _objc_ignored_method;
        cache_fill(cls, sel, imp, inst);
        goto done;
    }

    // Try this class's cache.

    imp = cache_getImp(cls, sel);
    if (imp) goto done;

    // Try this class's method lists.

    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.

    curClass = cls;
    while ((curClass = curClass->superclass)) {
        // 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.
        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();
        _class_resolveMethod(cls, sel, inst);
        // 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.unlockRead();

    // paranoia: look for ignored selectors with non-ignored implementations
    assert(!(ignoreSelector(sel)  &&  imp != (IMP)&_objc_ignored_method));

    // paranoia: never let uncached leak out
    assert(imp != _objc_msgSend_uncached_impcache);

    return imp;
}

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

推荐阅读更多精彩内容