`
liubo0_0
  • 浏览: 20077 次
社区版块
存档分类
最新评论

消息转发机制

    博客分类:
  • IOS
阅读更多

之前想了解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

 

  • 大小: 28 KB
0
0
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics