原文地址 :Runtime那些事兒(消息機(jī)制)
總結(jié):當(dāng)找不到對應(yīng)的IML方法時(shí)脸侥,RunTime會(huì)嘗試通過用戶設(shè)定的三種方法之一補(bǔ)救
補(bǔ)救一:更換/添加方法
+ (BOOL)resolveInstanceMethod:(SEL)sel
其中如果添加了函數(shù)實(shí)現(xiàn)則返回YES;
例
+ (BOOL)resolveInstanceMethod:(SEL)sel{
if (sel == @selector(doNothing)) {
NSLog(@"add Method");
class_addMethod([self class], sel, (IMP)doSomething, "v@:");
}
return [super resolveInstanceMethod:sel];
}
void doSomething(id self,SEL _cmd){
NSLog(@"doSomething");
}
- 關(guān)于
OBJC_EXPORT BOOL class_addMethod(Class cls, SEL name, IMP imp, const char *types)
參數(shù)說明:
cls: 類
SEL: 方法名
IMP:函數(shù)實(shí)現(xiàn)
types:函數(shù)格式,"v@:"建邓,其中v就是void,帶表返回類型就是空睁枕,@代表參數(shù)官边,這里指的是id(self)沸手,這里:指的是方法SEL(_cmd)
補(bǔ)救二:更換執(zhí)行對象
- (id)forwardingTargetForSelector:(SEL)aSelector
例:由SecondViewController來執(zhí)行這個(gè)方法
- (id)forwardingTargetForSelector:(SEL)aSelector{
return [[SecondViewController alloc] init];
}