在Objective-C中,是否有方法设置默认hander以避免unrecognizedselector
异常?我想使NSNULL
和NSNumber
响应NSString
中的所有方法。为“无法识别的选择器”异常设置默认处理程序
谢谢!
在Objective-C中,是否有方法设置默认hander以避免unrecognizedselector
异常?我想使NSNULL
和NSNumber
响应NSString
中的所有方法。为“无法识别的选择器”异常设置默认处理程序
谢谢!
处理“无法识别的选择”的例外,我们应该重写两个方法:
- (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,当对象没有匹配某个给定选择器的方法时调用它。
您可以使用类别将方法添加到NSNull
和NSNumber
类。阅读有关The Objective-C Programming Language中的类别。
您可以实施methodSignatureForSelector:
和forwardInvocation:
来处理任何消息,而不明确定义您要处理的所有消息。请阅读NSObject Class Reference。
太棒了!解决了:)谢谢! – Hang
谢谢!我注意到除了 - (void)forwardInvocation:(NSInvocation *)anInvocation,我还需要实现 - (NSMethodSignature *)methodSignatureForSelector:(SEL)选择器 – Hang