Unrecognized selector sent to instance error message from UIButton
-
14-11-2019 - |
Question
I have a UIButton that is added to a tableview programmatically. The problem is that when it is touched I run into the unrecognized selector sent to instance error message.
UIButton *alertButton = [UIButton buttonWithType:UIButtonTypeInfoDark];
[alertButton addTarget:self.tableView action:@selector(showAlert:)
forControlEvents:UIControlEventTouchUpInside];
alertButton.frame = CGRectMake(220.0, 20.0, 160.0, 40.0);
[self.tableView addSubview:alertButton];
and here's the alert method which I want to trigger when the InfoDark UIButton is touched:
- (void) showAlert {
UIAlertView *alert =
[[UIAlertView alloc] initWithTitle:@"My App"
message: @"Welcome to ******. \n\nSome Message........"
delegate:nil
cancelButtonTitle:@"Dismiss"
otherButtonTitles:nil];
[alert show];
[alert release];
}
thanks for any help.
Solution
Ok you have two problems. one is the selector issue as stated above, but your real problem is:
[alertButton addTarget:self.tableView
action:@selector(showAlert:)
forControlEvents:UIControlEventTouchUpInside];
This is the wrong target, unless you have subclassed UITableView to respond to the alert.
you want to change that code to:
[alertButton addTarget:self
action:@selector(showAlert)
forControlEvents:UIControlEventTouchUpInside];
OTHER TIPS
The reason of Crash : your showAlert
function prototype must be - (void) showAlert:(id) sender
.
Use below code
- (void) showAlert:(id) sender {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"My App" message: @"Welcome to ******. \n\nSome Message........" delegate:nil cancelButtonTitle:@"Dismiss" otherButtonTitles:nil];
[alert show];
[alert release];
}
As Jacob Relkin says in his answer here:
Because you included a colon (:) in your selector argument to addTarget, the receiving selector must accept a parameter. The runtime doesn't recognize the selector @selector(buttonTouched:), because there isn't a method with that name that accepts a parameter. Change the method signature to accept a parameter of type id to resolve this issue.
Jhaliya is correct, but here's a brief explanation of why.
When you configured the button's target, you defined the selector like this:
@selector( showAlert: )
The colon (:) establishes a method signature for the selector requiring one argument. However, your method was defined as -showAlert
, taking no arguments, so your object did not actually implement the method you told the UIButton
to invoke. Redefining your method as shown by Jhaliya will work, as will changing your button target's selector to:
@selector( showAlert )