OC消息轉發機制
阿新 • • 發佈:2019-03-21
clas style 轉發機制 sel 轉發 執行 添加 機制 signature
OC消息發送機制: 使用運行時,通過selector 去快速查找IMP(函數指針)的過程。
消息轉發:IMP找不到的時候,通過一些方法做轉發處理。
#import "Person.h" #import "Dog.h" #import "Animal.h" #import <objc/runtime.h> @implementation Person void runNew(id self, SEL sel) { NSLog(@"runNew------執行了"); } +(BOOL)resolveInstanceMethod:(SEL)sel {//在這個方法裏可以動態添加一個方法的實現 if (sel == @selector(run)) { class_addMethod(self, sel, (IMP)runNew, "v@:"); } return [super resolveInstanceMethod:sel]; } - (id)forwardingTargetForSelector:(SEL)aSelector { //在這個方法裏做消息分發處理 // if (aSelector == @selector(run)) { // return [[Dog alloc]init];//去執行dog類裏的run方法 // } // else if (aSelector == @selector(eat)) // { // return [[Animal alloc]init];//去執行Animal類裏的eat方法 // } return [super forwardingTargetForSelector:aSelector]; } - (void)forwardInvocation:(NSInvocation *)anInvocation { return [super forwardInvocation:anInvocation]; }-(NSMethodSignature *)methodSignatureForSelector:(SEL)aSelector { if (aSelector == @selector(run)) { return [NSMethodSignature signatureWithObjCTypes:"v@:"]; } if (aSelector == @selector(eat)) { return [NSMethodSignature signatureWithObjCTypes:"v@:"]; } return [NSMethodSignature methodSignatureForSelector:aSelector]; } -(void)doesNotRecognizeSelector:(SEL)aSelector { //最後, 都沒有找到方法實現, 則拋出異常,但程序不會崩潰 NSLog(@"%@---消息不存在",NSStringFromSelector(aSelector)); } @end
OC消息轉發機制