【发布时间】:2012-11-15 04:02:49
【问题描述】:
在 Objective-C 中,有没有办法设置默认处理程序以避免 unrecognizedselector 异常?我想让NSNULL 和NSNumber 响应NSString 中的所有方法。
谢谢!
【问题讨论】:
标签: objective-c cocoa nsstring unrecognized-selector
在 Objective-C 中,有没有办法设置默认处理程序以避免 unrecognizedselector 异常?我想让NSNULL 和NSNumber 响应NSString 中的所有方法。
谢谢!
【问题讨论】:
标签: objective-c cocoa nsstring unrecognized-selector
您可以使用类别将方法添加到NSNull 和NSNumber 类。阅读The Objective-C Programming Language 中的类别。
您可以实现methodSignatureForSelector: 和forwardInvocation: 来处理任何消息,而无需明确定义要处理的所有消息。在NSObject Class Reference 中了解它们。
【讨论】:
要处理“无法识别的选择器”异常,我们应该重写两个方法:
- (void)forwardInvocation:(NSInvocation *)anInvocation;
- (NSMethodSignature*)methodSignatureForSelector:(SEL)selector;
在这种情况下,如果我们希望 NSNull 在发生“无法识别的选择器”异常时执行 NSSString 方法,我们应该这样做:
@interface NSNull (InternalNullExtention)
@end
@implementation NSNull (InternalNullExtention)
- (NSMethodSignature*)methodSignatureForSelector:(SEL)selector
{
NSMethodSignature* signature = [super methodSignatureForSelector:selector];
if (!signature) {
signature = [@"" methodSignatureForSelector:selector];
}
return signature;
}
- (void)forwardInvocation:(NSInvocation *)anInvocation
{
SEL aSelector = [anInvocation selector];
if ([@"" respondsToSelector:aSelector])
[anInvocation invokeWithTarget:@""];
else
[self doesNotRecognizeSelector:aSelector];
}
@end
【讨论】:
有。查看 forwardInvocation 的示例:在此处的 NSObject 文档中: https://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSObject_Class/Reference/Reference.html
基本上你会覆盖 forwardInvocation 并且当一个对象没有匹配某个给定选择器的方法时调用它。
【讨论】: