Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to catch unrecognized selector sent to instance exception?

I am getting after some time unrecognized selector sent to instance exception. When i get this i want just skip it and my app should work.

However i don't know how to catch. As this don't catch:

@property(nonatomic,retain) UIButton *button;
    @try{

       if(button.currentBackgroundImage == nil){//rises exception 
    }
    }@catch(NSException *e){
}

How i could handle this ?

Thanks.

like image 930
Streetboy Avatar asked Jun 21 '12 05:06

Streetboy


People also ask

What is an unrecognized selector?

Once you run this line of code you will instantly get an error message in the console area, which look s like this (unrecognized selector sent to instance). Since the selector is another name for the method, the error is basically saying that it doesn't recognize the function that you're trying to call on this object.

What is #selector in Swift?

Use Selectors to Arrange Calls to Objective-C Methods In Objective-C, a selector is a type that refers to the name of an Objective-C method. In Swift, Objective-C selectors are represented by the Selector structure, and you create them using the #selector expression.


2 Answers

The technique I use and see often is: instead of catching the exception, check if the object responds to the selector:

if(![button respondsToSelector:@selector(currentBackgroundImage)] || button.currentBackgroundImage == nil) {
  // do your thing here...
}
like image 118
Chris Trahey Avatar answered Sep 28 '22 04:09

Chris Trahey


If you are getting this exception, it means there is a design flaw, a bug in your code. Patching it by ignoring the exception is not the right thing to do. Try to pin down why you are sending the wrong message to the wrong object instead. Your code will become more robust and maintainable.

Also, sometimes you get this exception when the object originally was of the right type, but is halfway in the process of being deallocated. Watch out!

If you still want to bypass the exception, read Apple's docs where it explains the multi-step process by which messages are bound to method implementations at run time. There is at least two places where you can catch it by overriding NSObject's default behavior.

like image 40
Nicolas Miari Avatar answered Sep 28 '22 06:09

Nicolas Miari