Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set default handler for "unrecognized selector" exception

In Objective-C, is there a way to set a default hander to avoid unrecognizedselector exception ? I want to make the NSNULL and NSNumber to response all the methods in NSString.

Thanks!

like image 738
Hang Avatar asked Nov 15 '12 04:11

Hang


3 Answers

You can use categories to add methods to the NSNull and NSNumber classes. Read about categories in The Objective-C Programming Language.

You can implement methodSignatureForSelector: and forwardInvocation: to handle any message without explicitly defining all of the messages you want to handle. Read about them in the NSObject Class Reference.

like image 193
rob mayoff Avatar answered Oct 17 '22 04:10

rob mayoff


To handle the "unrecognized selector" exception, we should override two methods:

- (void)forwardInvocation:(NSInvocation *)anInvocation;
- (NSMethodSignature*)methodSignatureForSelector:(SEL)selector;

In this case, if we want NSNull to perform the NSSString method if "unrecognized selector" exception occurred, we should do this:

@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
like image 38
Hang Avatar answered Oct 17 '22 04:10

Hang


There is. Look at the example for forwardInvocation: in the documentation for NSObject here: https://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSObject_Class/Reference/Reference.html

Basically you override forwardInvocation and that is called when an object does not have a method that matches some given selector.

like image 1
D.C. Avatar answered Oct 17 '22 05:10

D.C.