UIButton出现“Unrecognized selector sent to instance”错误消息

5

我有一个UIButton是通过编程方式添加到tableview中的。问题在于,当它被点击时,我遇到了无法识别的选择器发送到实例的错误消息。

    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];

这里是我想在点击 InfoDark UIButton 时触发的警报方法:

- (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];
}

感谢您的帮助。
3个回答

5

崩溃的原因:您的showAlert函数原型必须是- (void) showAlert:(id) sender

请使用以下代码:

- (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];
}

正如Jacob Relkin在他的回答中所说:

因为您在将selector参数添加到addTarget时包含了一个冒号(:),所以接收selector的方法必须接受一个参数。运行时无法识别选择器@selector(buttonTouched:),因为没有一个名为buttonTouched:的方法接受一个参数。更改方法签名以接受类型为id的参数即可解决此问题。


我将showAlert方法更改为showAlert:(id)sender。action:@selector(showAlert:)是否有任何更改?谢谢 - hanumanDev
@hanumanDev:只需将方法更改为showAlert:(id)sender,让您的操作保持不变(不要更改action:@selector(showAlert:))。 - Jhaliya - Praveen Sharma
我尝试修改了showAlert:(id)sender方法(在.h和.m文件中都有),但它仍然崩溃。 - hanumanDev
最终我在IB中完成了它,并将方法更改为IBAction,现在它可以工作了。我无法看出我的错误在哪里。不过还是感谢你的帮助。 - hanumanDev

5

好的,你有两个问题。 一个是如上所述的选择器问题,但你的真正问题是:

[alertButton addTarget:self.tableView 
                action:@selector(showAlert:) 
      forControlEvents:UIControlEventTouchUpInside];

这是错误的目标,除非您已经对UITableView进行了子类化以响应警报。

您需要将代码更改为:

[alertButton addTarget:self 
                action:@selector(showAlert) 
      forControlEvents:UIControlEventTouchUpInside];

3
Jhaliya是正确的,但这里简单解释一下为什么。
当你配置按钮的目标时,你定义了选择器,如下所示:
@selector( showAlert: )

冒号(:)为选择器建立方法签名,要求一个参数。然而,您的方法被定义为-showAlert,不需要参数,因此您的对象实际上没有实现您告诉UIButton调用的方法。重新定义您的方法,如Jhaliya所示,或更改您的按钮目标选择器为:
@selector( showAlert )

1
谢谢您的解释。我尝试了@selector(showAlert),但仍然出现未识别选择器错误。也许我还做错了其他事情。 - hanumanDev

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接