【问题标题】:Unrecognized Selector Sent To Instance, iPhone Error无法识别的选择器发送到实例,iPhone 错误
【发布时间】:2012-02-10 14:07:36
【问题描述】:

我得到了错误

“012-02-10 13:54:52.570 HelloWorld[14275:10103] -[HelloWorldViewController buttonPressed]:无法识别的选择器发送到实例 0x6cc0c50 2012-02-10 13:54:52.572 HelloWorld[14275:10103] * 由于未捕获的异常 'NSInvalidArgumentException' 导致应用程序终止,原因:'-[HelloWorldViewController buttonPressed]: 无法识别的选择器发送到实例 0x6cc0c50'"。

这是有问题的文字:

-(void)buttonPressed:(id)sender {
    UIButton *button = (UIButton*)sender;
    NSString *text = [button titleForState:UIControlStateNormal];
    NSLog(@"%@",text);
}

我知道这一点,因为如果我将代码更改为:

-(void)buttonPressed {
    NSLog(@"Button Pressed");
}

然后它就可以正常工作了。

但是,我需要发送消息的组件中的文本。组件不使用 IB 拖放。它们被分配、初始化并放置在 loadView 方法中。我为每个按钮添加了 buttonPressed 作为动作监听器。

【问题讨论】:

  • 你能显示添加动作监听器的代码吗?

标签: iphone ios uibutton unrecognized-selector method-invocation


【解决方案1】:

错误无法识别的选择器可能是由于缺少:

[yourbutton addTarget:self action:@selector(buttonPressed:) forControlEvents:UIControlEventTouchUpInside];

而不是

[yourbutton addTarget:self action:@selector(buttonPressed) forControlEvents:UIControlEventTouchUpInside];

在第一种情况下,您调用-(void)buttonPressed:(id)sender。在第二个中,您调用-(void)buttonPressed

但如果您为 UIButton 提供更多代码,则可能更容易理解发生了什么。

【讨论】:

  • 需要注意的是这个答案也适用于Swift。
【解决方案2】:

在第一个(不工作)情况下,您有-(void)buttonPressed:(id)sender,在第二个(工作)情况下,您有-(void)buttonPressed。显然,您的按钮调用该函数时不带参数。

【讨论】:

    【解决方案3】:

    当您为按钮触摸事件添加@selector(buttonPressed:) 时,可能会出现这种情况,您忘记将: 与方法名称放在一起。

    你可以检查一下。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-04-04
      • 1970-01-01
      • 2017-04-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多