无法识别的选择器从UIButton发送到实例错误消息

时间:2011-05-17 14:53:43

标签: ios objective-c iphone uibutton unrecognized-selector

我有一个以编程方式添加到tableview的UIButton。问题是当它被触摸时我遇到无法识别的选择器发送到实例错误消息。

    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 个答案:

答案 0 :(得分: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在他的回答here中所说:

  

因为你包含了冒号(:)   你的选择器参数addTarget,   接收选择器必须接受a   参数。运行时没有   识别选择器   @selector(buttonTouched :),因为   没有一个具有该名称的方法   接受参数。改变   方法签名接受参数   类型为id以解决此问题。

答案 1 :(得分:5)

好的,你有两个问题。 一个是上面提到的选择器问题,但你真正的问题是:

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

这是错误的目标,除非您已将UITableView子类化以响应警报。

您想将该代码更改为:

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

答案 2 :(得分:3)

Jhaliya是对的,但这是对原因的简要解释。

配置按钮的目标时,您可以像这样定义选择器:

@selector( showAlert: )

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

@selector( showAlert )