消息转发机制

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

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值