在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