| 說明 | 時(shí)間 |
|---|---|
| 首次發(fā)布 | 2017年08月09日 |
| 最近更新 | 2019年05月04日 |
消息機(jī)制可以認(rèn)為是objc_msgSend的執(zhí)行流程,包括消息發(fā)送、動(dòng)態(tài)方法解析和消息轉(zhuǎn)發(fā)。
一、消息發(fā)送

消息發(fā)送
二、動(dòng)態(tài)方法解析
- 檢查是否曾經(jīng)有動(dòng)態(tài)解析
- 有:消息轉(zhuǎn)發(fā)
- 沒有:調(diào)用
+ (BOOL)resolveInstanceMethod:(SEL)sel或+ (BOOL)resolveClassMethod:(SEL)sel來動(dòng)態(tài)解析,并將標(biāo)記置為YES。
注意:在動(dòng)態(tài)解析后,會(huì)重新回到 消息發(fā)送 的流程。
示例:
//MZPerson.h
#import <Foundation/Foundation.h>
@interface MZPerson : NSObject
- (void)sayHello;
- (void)sayWorld;
+ (void)unimplementationClassMethod;
@end
//MZPerson.m
#import "MZPerson.h"
#import <objc/runtime.h>
@implementation MZPerson
/**
動(dòng)態(tài)添加方法之成員方法
*/
- (void)addByMethod {
NSLog(@"%@--%s--%s", self, sel_getName(_cmd), __func__);
}
void addByFunction(id self, SEL _cmd) {
NSLog(@"%@--%s--%s", self, sel_getName(_cmd), __func__);
}
+ (BOOL)resolveInstanceMethod:(SEL)sel {
//通過C函數(shù)實(shí)現(xiàn)
if (sel == @selector(sayHello)) {
//types:類型編碼, v表示void, @表示id或NSObject*, :表示SEL. 這些都可以用@encode()查看
class_addMethod(self, sel, (IMP)addByFunction, "v@:");
//return YES/NO都是無所謂的,只是方便底層打印而已.但最好還是按規(guī)范來,YES表示添加了方法到接受者
return YES;
}
//通過OC方法實(shí)現(xiàn)
if (sel == @selector(sayWorld)) {
Method method = class_getInstanceMethod(self, @selector(addByMethod));
class_addMethod(self, sel, method_getImplementation(method), method_getTypeEncoding(method));
return YES;
}
return [super resolveInstanceMethod:sel];
}
+ (BOOL)resolveClassMethod:(SEL)sel {
//通過C函數(shù)實(shí)現(xiàn)
if (sel == @selector(unimplementationClassMethod)) {
//需要特別注意的是,類方法存放在元類里,所以這里要把方法添加到object_getClass(self)
class_addMethod(object_getClass(self), sel, (IMP)addByFunction, "v@:");
return YES;
}
return [super resolveClassMethod:sel];
}
@end
三、消息轉(zhuǎn)發(fā)
消息轉(zhuǎn)發(fā)分為兩個(gè)階段:
第一階段:- (id)forwardingTargetForSelector:(SEL)aSelector;
第二階段:- (NSMethodSignature *)methodSignatureForSelector:(SEL)aSelector和- (void)forwardInvocation:(NSInvocation *)anInvocation;
當(dāng)階段一沒有實(shí)現(xiàn),或者返回nil的時(shí)候,則進(jìn)行階段二;如果消息轉(zhuǎn)發(fā)處理的是成員方法,那么三個(gè)階段都使用成員方法,否則就使用類方法。如代碼里所示。

消息轉(zhuǎn)發(fā)圖示
//消息轉(zhuǎn)發(fā)第一階段
//底層是通過`id cls = object_getClass(receiver);`拿到receiver
- (id)forwardingTargetForSelector:(SEL)aSelector {
if (aSelector == @selector(sayHello)) {
// //sayHello是對象方法,則返回的必須是一個(gè)對象,并且該對象中有成員方法sayHello
// //返回nil,則直接進(jìn)入消息轉(zhuǎn)發(fā)的第二個(gè)階段
return [GoodGuy new];
}
return [super forwardingTargetForSelector:aSelector];
}
//消息轉(zhuǎn)發(fā)第二階段(該部分是針對成員方法)
- (NSMethodSignature *)methodSignatureForSelector:(SEL)aSelector {
if (aSelector == @selector(sayHello)) {
return [NSMethodSignature signatureWithObjCTypes:"v@:@q"];
}
return [super methodSignatureForSelector:aSelector];
}
- (void)forwardInvocation:(NSInvocation *)anInvocation {
//可以用anInvocation里的selector; 也可以自己直接指定一個(gè)方法
anInvocation.selector = @selector(offerHelp:age:);
NSString *name = @"小紅";
NSInteger age = 18;
//每一個(gè)方法會(huì)默認(rèn)隱藏兩個(gè)參數(shù):self、_cmd,所以自定義參數(shù)要從下標(biāo)2開始
[anInvocation setArgument:&name atIndex:2];
[anInvocation setArgument:&age atIndex:3];
GoodGuy *goodguy = [GoodGuy new];
//做個(gè)判斷,保證指定的receiver會(huì)響應(yīng)該selector
if ([goodguy respondsToSelector:anInvocation.selector]) {
[anInvocation invokeWithTarget:goodguy];
}
}
//以下是針對于類方法的消息轉(zhuǎn)發(fā)(區(qū)別只是將這兩個(gè)方法換成`+`即可)
//消息轉(zhuǎn)發(fā)第一階段
+ (id)forwardingTargetForSelector:(SEL)aSelector {
if (aSelector == @selector(unimplementationClassMethod)) {
//返回nil,則直接進(jìn)入消息轉(zhuǎn)發(fā)的第二個(gè)階段
//消息轉(zhuǎn)發(fā)類方法,這里需要傳入一個(gè)類對象
return [GoodGuy class];
}
return [super forwardingTargetForSelector:aSelector];
}
+ (NSMethodSignature *)methodSignatureForSelector:(SEL)aSelector {
if (aSelector == @selector(unimplementationClassMethod)) {
//如果需要傳參,則ObjCTypes一定要寫寫清,不然在傳參時(shí)會(huì)報(bào)越界
//如果需要進(jìn)行消息轉(zhuǎn)發(fā)給一個(gè)`無參無返回值`的方法,無論被轉(zhuǎn)發(fā)的selector是什么類型的,通通可以用@"v@:"來表示
return [NSMethodSignature signatureWithObjCTypes:"v@:@q"];
}
return [super methodSignatureForSelector:aSelector];
}
+ (void)forwardInvocation:(NSInvocation *)anInvocation {
//可以用anInvocation里的selector; 也可以自己直接指定一個(gè)方法
anInvocation.selector = @selector(offerHelp:age:);
NSString *name = @"小紅";
NSInteger age = 18;
//每一個(gè)方法會(huì)默認(rèn)隱藏兩個(gè)參數(shù):self、_cmd,所以自定義參數(shù)要從下標(biāo)2開始
[anInvocation setArgument:&name atIndex:2];
[anInvocation setArgument:&age atIndex:3];
GoodGuy *goodguy = [GoodGuy new];
//做個(gè)判斷,保證指定的receiver會(huì)響應(yīng)該selector
if ([goodguy respondsToSelector:anInvocation.selector]) {
[anInvocation invokeWithTarget:goodguy];
}
}
拓展
消息轉(zhuǎn)發(fā)還可以用于降低 unrecognized selector 的崩潰率。
示例:
#import <Foundation/Foundation.h>
@interface MZPerson : NSObject
- (void)printPerson:(NSString *)name age:(NSInteger)age;
@end
@implementation MZPerson
- (NSMethodSignature *)methodSignatureForSelector:(SEL)aSelector {
// 能響應(yīng)的直接走原先的邏輯
if ([self respondsToSelector:aSelector]) {
return [super methodSignatureForSelector:aSelector];
}
// 找不到的方法
return [NSMethodSignature signatureWithObjCTypes:"v@:"];
}
// 找不到的方法,都會(huì)來到這里
- (void)forwardInvocation:(NSInvocation *)anInvocation {
NSLog(@"找不到%@方法", NSStringFromSelector(anInvocation.selector));
}
@end
int main(int argc, const char * argv[]) {
@autoreleasepool {
MZPerson *person = [[MZPerson alloc] init];
//MZPerson里并沒有實(shí)現(xiàn)`printPerson:age:`的方法
[person printPerson:@"LynnZhang" age:12];
}
return 0;
}