2012-11-15 36 views

回答

3

處理「無法識別的選擇」的例外,我們應該重寫兩個方法:

- (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 
1

有。看看forwardInvocation的例子:在這裏NSObject的文檔中: https://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSObject_Class/Reference/Reference.html

基本上你覆蓋forwardInvocation,當對象沒有匹配某個給定選擇器的方法時調用它。

+0

謝謝!我注意到除了 - (void)forwardInvocation:(NSInvocation *)anInvocation,我還需要實現 - (NSMethodSignature *)methodSignatureForSelector:(SEL)選擇器 – Hang

3

您可以使用類別將方法添加到NSNullNSNumber類。閱讀有關The Objective-C Programming Language中的類別。

您可以實施methodSignatureForSelector:forwardInvocation:來處理任何消息,而不明確定義您要處理的所有消息。請閱讀NSObject Class Reference

+0

太棒了!解決了:)謝謝! – Hang

相關問題