unrecognizedselector
Objective-C では、例外を回避するためにデフォルトのハンドラを設定する方法はありますか? 内のすべてのメソッドを応答するNSNULL
andを作成したい。NSNumber
NSString
ありがとう!
unrecognizedselector
Objective-C では、例外を回避するためにデフォルトのハンドラを設定する方法はありますか? 内のすべてのメソッドを応答するNSNULL
andを作成したい。NSNumber
NSString
ありがとう!
NSNull
カテゴリを使用して、およびNSNumber
クラスにメソッドを追加できます。The Objective-C Programming Language のカテゴリについてお読みください。
処理するすべてのメッセージを明示的に定義しなくても、任意のメッセージを実装methodSignatureForSelector:
しforwardInvocation:
て処理できます。NSObject Class Referenceでそれらについて読んでください。
「認識されないセレクター」例外を処理するには、2 つのメソッドをオーバーライドする必要があります。
- (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をオーバーライドします。これは、オブジェクトに特定のセレクターに一致するメソッドがない場合に呼び出されます。