2012-11-15 35 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

相关问题