之前想了解runtime的先关知识,无意中发现了消息转发机制,就自己动手写了些。
如上图所示:在oc中调用方法时,本类及父类找不到此方法时,有如下步骤。
要重写一下方法。
第一步:尝试动态方法解析
- void dynamicMethod(id self, SEL _cmd)
- {
- printf("SEL %s did not exist\n",sel_getName(_cmd));
- }
- + (BOOL) resolveInstanceMethod:(SEL)aSEL
- {
- class_addMethod([self class], aSEL, (IMP)dynamicMethod, "v@:");
- return YES;
- }
第二步:如果第一步返回NO,则进行【尝试快速消息转发】
- -(id)forwardingTargetForSelector:(SEL)aSelector
- {
- Proxy *p = [[Proxy alloc] init];
- if ([p respondsToSelector:aSelector])
- {
- return p;
- }
- return nil;
- }
第三步:如果第第二步返回nil,则进行【尝试标准消息转发】
- //检测此消息是否有效。
- -(NSMethodSignature *) methodSignatureForSelector:(SEL)aSelector
- {
- return [Proxy instanceMethodSignatureForSelector:aSelector];
- }
- -(void)forwardInvocation:(NSInvocation *)anInvocation
- {
- SEL name = [anInvocation selector];
- NSLog(@" >> forwardInvocation for selector %@", NSStringFromSelector(name));
- Proxy * proxy = [[Proxy alloc] init];
- if ([proxy respondsToSelector:name]) {
- [anInvocation invokeWithTarget:proxy];
- }
- else {
- [super forwardInvocation:anInvocation];
- }
- }
注:
调用函数:
- [foo performSelector:@selector(MissMethod)];
Proxy类
- @implementation Proxy
- -(void)MissMethod
- {
- NSLog(@" >> MissMethod() called in Proxy.");
- }
- @end