iOS how to catch exception unrecognized selector sent to instance when target object is NULL already?
I read alot about what is the problem for exception "unrecog..." But i need something else
I have view with two buttons: Start and Delete, also i have two UILabels: oneLabel and secondLabel
So the I press button Start I start NSOperation thread started
And I give him labels (oneLabel,secondLabel) as params
to change text of labels on main loop i use
[oneLabel performSelectorOnMainThread:@selector(setText:) withObject:someString waitUntilDone:YES];
All works fine, but when i press button Delete - it's deleting secondLabel from view with method
[secondLabel removeFromSuperview]
and then
s开发者_开发问答econdLabel=nil;
So, after what i get exception. I understand why it happened - because the target object for message with selector setText if not available now becaus it's nil.
And i get exception and app crashes.
How i can Catch this exception in this case?
For what i need it for? When use tableView controller with ImageView wich loads images in separate thread.
try this:
id yourObject;
if (yourObject != nil && [yourObject respondsToSelector:@selector(yourSelector)]) {
// Do your stuff here
}
This will only call your method to be executed if your objects is still available and it responds to the specifed selector.
Hope this helps, Vlad
setText:
it is not an object, it should be a method in your implementation. someString
is the object that is send to the setText
method.
When the command
[oneLabel performSelectorOnMainThread:@selector(setText:) withObject:someString waitUntilDone:YES];
is executed, then the method setText is called.
You are seeing unrecognized selector sent to instance
because the method
-(void)setText:(id)sender
does not exist or you have misspelled it.
You dont need to catch the exception. You can make a method that waits for the selector to excecute and catches it when it is really available.
You need to probably remake the secondLabel if I understood correctly because you are deleting it. Do this first and the exception won't be there to catch.
This is not a problem to send a message to nil, it is legal. Unrecognised selector exception means you have wrong spelling in your method name. A common mistake is to forget the colon if the method requires a parameter. For example @selector(setText) when you meant @selector(setText:).
精彩评论