什么是消息转发机制?
众所周知,在Objective-C语言中,方法的调用过程其实就是一个消息的发送过程,作为消息发送,难免会有找到接收者、或者是接收者不具备接收消息能力的情况,如此,就会进入一个新的流程,也就是消息转发流程。那么消息转发机制又分为哪些流程呢?
消息转发三部曲
消息转发机制分为三个流程:
- 动态方法分析:动态的处理找不到的接收者的方法
- 消息转发:找别的对象处理相关消息
- 消息签名、分发
下面我们就具体的分析每一个流程:
动态方法分析
消息的发送过程其实就是一个寻找IMP的过程,动态方法分析就是我们动态的为没有定义/实现的方法添加IMP。
由于方法分为实例方法和类方法,所以动态方法分析也分为实例动态方法分析和类动态方法分析
。
+ (BOOL)resolveInstanceMethod:(SEL)sel {
//
}
+ (BOOL)resolveClassMethod:(SEL)sel {
//
}
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]
_class_resolveClassMethod(cls, sel, inst);
if (!lookUpImpOrNil(cls, sel, inst,
NO/*initialize*/, YES/*cache*/, NO/*resolver*/))
{
_class_resolveInstanceMethod(cls, sel, inst);
}
}
}
首先我们来看动态实例方法分析的相关代码:
static void _class_resolveInstanceMethod(Class cls, SEL sel, id inst)
{
// 查看类、父类、根类是否实现动态分析方法,没有实现就直接返回
// 实现了就接着往下走看是否在动态方法里添加了IMP
if (! lookUpImpOrNil(cls->ISA(), SEL_resolveInstanceMethod, cls,
NO/*initialize*/, YES/*cache*/, NO/*resolver*/))
{
// Resolver not implemented.
return;
}
// 系统给你一次机会 - 你要不要针对 sel 来操作一下下
BOOL (*msg)(Class, SEL, SEL) = (typeof(msg))objc_msgSend;
bool resolved = msg(cls, SEL_resolveInstanceMethod, sel);
// Cache the result (good or bad) so the resolver doesn't fire next time.
// +resolveInstanceMethod adds to self a.k.a. cls
// 如果在resolveInstanceMethod做了处理,此处就会找到IMP,然后会继续走方法查找流程
IMP imp = lookUpImpOrNil(cls, sel, inst,
NO/*initialize*/, YES/*cache*/, NO/*resolver*/);
}
IMP lookUpImpOrNil(Class cls, SEL sel, id inst,
bool initialize, bool cache, bool resolver)
{
IMP imp = lookUpImpOrForward(cls, sel, inst, initialize, cache, resolver);
if (imp == _objc_msgForward_impcache) return nil;
else return imp;
}
由代码可知,当我们使用实例动态方法解析的时候,需要重写resolveInstanceMethod方法,并且给消息接收者指定一个IMP,这样在方法查找的时候就会找到需要的IMP,从而使方法正常调用,避免了找不到方法的实现而出现的崩溃。看下面的例子,当调用sayNB的时候,由于TPerson并没有实现sayNB方法,必然会崩溃,此时我们重写resolveInstanceMethod,并在resolveInstanceMethod为sayNB添加了sayHello的IMP,如此会进入消息转发第一步(动态方法分析),给[person sayNB]返回了sayHello的实现了。
eg:
@interface TPerson : NSObject
- (void)sayNB;
- (void)sayHello;
+ (void)sayHappay;
+ (void)sayYo;
@end
#import "TPerson.h"
#import <objc/message.h>
@implementation TPerson
- (void)sayHello {
NSLog(@"%s",__func__);
}
+ (void)sayHappay {
NSLog(@"%s",__func__);
}
+ (BOOL)resolveInstanceMethod:(SEL)sel {
if (sel == @selector(sayNB)) {
IMP sayNBIMP = class_getMethodImplementation(self, @selector(sayHello));
Method sayNBMethod = class_getInstanceMethod(self, @selector(sayHello));
const char *sayNBType = method_getTypeEncoding(sayNBMethod);
return class_addMethod(self, sel, sayNBIMP, sayNBType);
}
return [super resolveInstanceMethod:sel];
}
+ (BOOL)resolveClassMethod:(SEL)sel{
if (sel == @selector(sayYo)) {
IMP sayHIMP = class_getMethodImplementation(objc_getMetaClass("TPerson"), @selector(sayHappay));
Method sayHMethod = class_getClassMethod(objc_getMetaClass("TPerson"), @selector(sayHappay));
const char *sayHType = method_getTypeEncoding(sayHMethod);
return class_addMethod(objc_getMetaClass("TPerson"), sel, sayHIMP, sayHType);
}
return [super resolveClassMethod:sel];
}
@end
#import "TPerson.h"
#import <objc/runtime.h>
int main(int argc, const char * argv[]) {
@autoreleasepool {
TPerson *person = [[TPerson alloc] init];
[person sayNB];
[TPerson sayYo];
}
return 0;
}
+ (BOOL)resolveClassMethod:(SEL)sel {
}
static void _class_resolveClassMethod(Class cls, SEL sel, id inst)
{
assert(cls->isMetaClass());
if (! lookUpImpOrNil(cls, SEL_resolveClassMethod, inst,
NO/*initialize*/, YES/*cache*/, NO/*resolver*/))
{
// Resolver not implemented.
return;
}
BOOL (*msg)(Class, SEL, SEL) = (typeof(msg))objc_msgSend;
bool resolved = msg(_class_getNonMetaClass(cls, inst),
SEL_resolveClassMethod, sel);
// Cache the result (good or bad) so the resolver doesn't fire next time.
// +resolveClassMethod adds to self->ISA() a.k.a. cls
IMP imp = lookUpImpOrNil(cls, sel, inst,
NO/*initialize*/, YES/*cache*/, NO/*resolver*/);
}
同理,在类动态方法解析里,我们同样是需要实现resolveClassMethod方法,并且在该方法里给消息接收者指定一个IMP。需要注意的是,当执行类动态方法分析的时候,也会执行一次实例动态方法分析,因为类方法是存在元类中,当我们遍历元类的父类的时候,根元类的父类是NSObject,所以还会在NSObject类中查找一下其对应的实例方法。
根据上面的例子,我们也可以验证这个结论。
消息转发:找别的对象处理相关消息
当我们没有在动态方法解析中处理消息转发的时候,就会进入消息转发第二步:找别的对象处理该方法。当我们给该对象提供另一个对象,该对象能够处理当前的SEL,转发的消息就会正常执行。否则就会进入第三步。
eg:
@interface TPerson : NSObject
- (void)sayNB;
@end
#import "TPerson.h"
#import <objc/message.h>
@implementation TPerson
- (id)forwardingTargetForSelector:(SEL)aSelector{
if (aSelector == @selector(sayNB)) {
return [TPeople alloc];
}
return [super forwardingTargetForSelector:aSelector];
}
@end
@interface TPeople : NSObject
- (void)sayNB;
@end
#import "TPeople.h"
#import <objc/message.h>
@implementation TPeople
- (void)sayNB {
NSLog(@"%s",__func__);
}
@end
#import "TPerson.h"
#import <objc/runtime.h>
int main(int argc, const char * argv[]) {
@autoreleasepool {
TPerson *person = [[TPerson alloc] init];
[person sayNB];
}
return 0;
}
消息签名、分发
在消息转发第二步,如果有没有对象可以处理该消息,那么就会进入到第三步,对方法进行签名、分发,统一处理。
- (NSMethodSignature *)methodSignatureForSelector:(SEL)aSelector{
NSLog(@"%s -- %@",__func__,NSStringFromSelector(aSelector));
if (aSelector == @selector(sayNB)) { // v @ :
return [NSMethodSignature signatureWithObjCTypes:"v@:"];
}
return [super methodSignatureForSelector:aSelector];
}
//
- (void)forwardInvocation:(NSInvocation *)anInvocation{
NSLog(@"%s ",__func__);
// SEL aSelector = [anInvocation selector];
// if ([[TPeople alloc] respondsToSelector:aSelector]) {
// [anInvocation invokeWithTarget:[TPeople alloc]];
// } else {
// [super forwardInvocation:anInvocation];
// }
}
总结
方法查找在抛出异常之前也就是消息转发过程中都经过了以下这些步骤:
- 对象在收到无法解读的消息后,首先会调用
+ (BOOL)resolveInstanceMethod:(SEL)sel;
+ (BOOL)resolveClassMethod:(SEL)sel;
询问是否有动态添加方法来进行处理。如果有,消息转发过程提前结束,没有则就会进行第二步
- 问问有没有别的类能够帮忙处理一下,调用的是
- (id)forwardingTargetForSelector:(SEL)aSelector
因为这个方法返回的是一个对象,如果返回能处理的类,消息转发流程结束;如果没有能处理的类,进入第三步
- 方法签名、分发
// 获取这个selector的方法签名
- (NSMethodSignature *)methodSignatureForSelector:(SEL)aSelector
// 通过anInvocation拿到相应信息做处理
- (void)forwardInvocation:(NSInvocation*)anInvocation
- 最后消息未能处理的时候,还会调用到
- (void)doseNotRecognizeSelector:(SEL)
Tips: 方法签名
iOS中的方法签名是通过NSMethodSignature实现。
+ (nullable NSMethodSignature*)signatureWithObjCTypes:(const char *)types;
- (NSMethodSignature *)methodSignatureForSelector:(SEL)aSelector;
+ (NSMethodSignature *)instanceMethodSignatureForSelector:(SEL)aSelector
方法签名type的实现:
eg: 如[person sayNB] 返回时空,传入的参数是id,SEL,所以Type Encodings是@“v@:”
Type Encodings:
Code | Meaning |
---|---|
c | A char |
i | An int |
s | A short |
l | A long |
l | is treated as a 32-bit quantity on 64-bit programs |
q | A long long |
C | An unsigned char |
I | An unsigned int |
S | An unsigned short |
L | An unsigned long |
Q | An unsigned long long |
f | A float |
d | A double |
B | A C++ bool or a C99 _Bool |
v | A void |
* | A character string (char *) |
@ | An object (whether statically typed or typed id) |
# | A class object (Class) |
: | A method selector (SEL) |
[array type] | An array |
{name=type...} | A structure |
(name=type...) | A union |
bnum | A bit field of num bits |
^type | A pointer to type |
? | An unknown type (among other things, this code is used for function pointers) |