Unrecognized selector sent to instance error message from UIButton

hanumanDev picture hanumanDev · May 17, 2011 · Viewed 9.4k times · Source

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.

Answer

Jhaliya - Praveen Sharma picture Jhaliya - Praveen Sharma · May 17, 2011

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.