小编Jie*_* Wu的帖子

如何通过消息转发"吞下""无法识别的选择器错误"?

我只是在研究Objective-C的"消息转发".我编写了一个测试程序来验证我是否可以在运行时"吞下"一个无法识别的选择器.所以我这样做了:

- (void) forwardInvocation: (NSInvocation *) anInvocation {
    if ([anInvocation selector] == @selector(testMessage)){
       NSLog(@"Unknow message");
    }
    return;
}
Run Code Online (Sandbox Code Playgroud)

但它仍然在运行时抛出"无法识别的选择器"错误.在搜索了解决方案后,我知道我需要覆盖方法"methodSignatureForSelector:",所以我编写了另一个名为"Proxy"的代理类,并使用以下方法:

(NSMethodSignature *)methodSignatureForSelector:(SEL)selector {
    if ([Proxy instancesRespondToSelector: selector]) {
        return [Proxy instanceMethodSignatureForSelector: selector];
    }   
    return [super methodSignatureForSelector:selector];
}
Run Code Online (Sandbox Code Playgroud)

但实际上,我不想实现这样的另一个代理类来完成这个方法.我想做的就是忽略这个未知的选择器.但是,如果我只是键入它,它不起作用:

(NSMethodSignature *)methodSignatureForSelector:(SEL)selector {   
    return [super methodSignatureForSelector:selector];
}
Run Code Online (Sandbox Code Playgroud)

所以,我想知道有什么办法可以简单地"吞下"这个错误吗?(不使用异常处理程序,我想采用"转发"方式).谢谢!

objective-c message-forwarding

5
推荐指数
1
解决办法
881
查看次数

标签 统计

message-forwarding ×1

objective-c ×1