动态方法解析:

方法没有查询到的时候,运行时会调用 - (BOOL)resolveInstanceMethod:或者 + (BOOL)resolveClassMethod:,定义在NSObject中,默认实现如下:

+ (BOOL)resolveClassMethod:(SEL)sel {
    return NO;
}

+ (BOOL)resolveInstanceMethod:(SEL)sel {
    return NO;
}

即默认不会进行动态方法解析,如果在自定义的类中重写了该函数并且添加了动态解析方法, 那消息查找的最后阶段就会调用到动态解析方法。以实例方法为例如下:

+ (BOOL)resolveInstanceMethod:(SEL)sel {
    if (sel == @selector(MissMethod)) {
        class_addMethod([self class], sel, (IMP)dynamicIMP, "v@:");
        return YES;
    }
    return [super resolveInstanceMethod:sel];
}

“v@:“中v代表函数返回值类型为void,@代表self的类型为id,:代表_cmd的类型为SEL。当调用到MissMethod的时候,就会执行dynamicIMP方法

消息转发:

动态方法解析失败后流程会被标记,随即再次触发消息查询,此时会跳过动态方法解析流程直接进行消息转发。同样定义在NSObject中,以对象方法为例- (id)forwardingTargetForSelector:(SEL)aSelector默认实现如下:

- (id)forwardingTargetForSelector:(SEL)aSelector {
    return nil;
}

默认返回nil不修改消息接受者,修改如下,这样当对象接收到MissMethod消息的时候,就会执行CommonClass的MissMethod方法,当然会走一次CommonClass的消息查找流程

- (id)forwardingTargetForSelector:(SEL)aSelector {
    if(aSelector == @selector(MissMethod)) {
        return [[CommonClass alloc] init];
    }
    return [super forwardingTargetForSelector:aSelector];
}

获取方法签名执行完整消息转发:

当消息转发失败的时候,会执行methodSignatureForSelector获取方法签名,获取成功后会执行forwardInvocation进行消息分发,以对象方法为例默认实现如下:

// Replaced by CF (returns an NSMethodSignature)
- (NSMethodSignature *)methodSignatureForSelector:(SEL)sel {
    _objc_fatal("-[NSObject methodSignatureForSelector:] "
                "not available without CoreFoundation");
}

- (void)forwardInvocation:(NSInvocation *)invocation {
    [self doesNotRecognizeSelector:(invocation ? [invocation selector] : 0)];
}

默认会执行doesNotRecognizeSelector直接抛出异常,修改如下

- (NSMethodSignature *)methodSignatureForSelector:(SEL)aSelector {
    NSMethodSignature *methodSignature = [super methodSignatureForSelector:aSelector];
    if (!methodSignature) {
        methodSignature = [NSMethodSignature signatureWithObjCTypes:"v@:*"];
    }
    return methodSignature;
}

- (void)forwardInvocation:(NSInvocation *)invocation {
    SEL sel = invocation.selector;
    CommonClass *obj = [[CommonClass alloc] init];
    if([obj respondsToSelector:sel]) {
        [invocation invokeWithTarget:obj];
    } else {
        [self doesNotRecognizeSelector:sel];
    }
}

如上获取成功的方法签名用于生成NSInvocation对象,invocation对象通过invokeWithTarget:方法将消息发送给obj对象,同样会走一遍CommonClass的消息查找流程,值得注意的是这里可以同时发送消息给多个对象,对于一些一对多的传值模型可以考虑用这种方案

总结

可以看到苹果的消息转发机制是很有逻辑的

1.消息查找阶段没有匹配到IMP,会进入方法动态解析流程,执行resolveInstanceMethod,你可能想在本类搞些事情
2.动态解释流程失败后进入消息转发流程,执行forwardingTargetForSelector,你可能想在其他类搞些事情
3.消息转发流程失败后会启动完整消息转发机制,获取方法签名methodSignatureForSelector,执行forwardInvocation方法进行消息分发,你可能在其他很多类搞很多事情