Han*_*ang 5 cocoa objective-c nsstring unrecognized-selector
在Objective-C中,有没有办法设置默认的处理程序以避免unrecognizedselector异常?我想做NSNULL和NSNumber响应所有的方法NSString.
谢谢!
为了处理“无法识别的选择器”异常,我们应该重写两个方法:
- (void)forwardInvocation:(NSInvocation *)anInvocation;
- (NSMethodSignature*)methodSignatureForSelector:(SEL)selector;
Run Code Online (Sandbox Code Playgroud)
在这种情况下,如果我们希望 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
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1506 次 |
| 最近记录: |