从 OC 转发机制说起
在 OC 中,方法调用也被称为发送消息,向一个
的方法进行调用的时候,其实底层都会转换成 objc_msgSend 方法来进行.
如
[XXObject hello]会转换成objc_msgSend(XXObject,@selector(hello))
通过 objc_msgSend 来进行寻找方法,缓存并且调用方法等一系列的过程。
如果你发送的消息的实现不存在,并不会立即 Crash,反而有几个机会可以弥补,这个就是 Runtime 的消息转发。其过程由一下几步组成
- 如果是类方法不存在则会调用
resolveClassMethod:
,如果是一个实例方法,那么会调用resolveInstanceMethod:
方法,这个时候可以将实现动态的添加到相应的类中,并且返回 YES, 如果返回 NO 则会进入到下一步。 - 此时
forwardingTargetForSelector:
将会被调用, 你可以在这个方法寻找一个合适的执行者,并向这个 target 转发消息。 - 如果前 2 步都是失败的那么
methodSignatureForSelector:
会被调用。你可以在此方法生成方法签名,为下一步做准备 - 之后来到
forwardInvocation
方法来进行最终的方法调用,你可以指向其他类来 invoke 这个 Invocation 已达到转发执行的目的。 - 当所有方法都失败,最后只能走到终点
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;
}