iOS开发之Runtime-消息转发

286 阅读4分钟

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

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

一、动态方法解析: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次机会让我们进行处理。 下面是动态方法解析和消息转发的流程:

五、源码

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

/***********************************************************************
* 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;
}