【问题标题】:Unrecognized selector sent to instance error when I click my buttons [duplicate]单击按钮时,无法识别的选择器发送到实例错误[重复]
【发布时间】:2018-07-20 19:00:13
【问题描述】:

我花了一天时间试图弄清楚为什么每次单击代码中生成的按钮之一时都会出现此错误:

-[HomeViewController aMethod:]: 无法识别的选择器发送到实例 0x102813a00 * 由于未捕获的异常“NSInvalidArgumentException”而终止应用程序,原因:“-[HomeViewController aMethod:]:无法识别的选择器发送到实例 0x102813a00” * 首先抛出调用栈: (0x184e83164 0x1840cc528 0x184e90628 0x18e7fe188 0x184e88b10 0x184d6dccc 0x18e4725cc 0x18e47254c 0x18e45d0f4 0x18e47a368 0x18eacd5e4 0x18eac8b94 0x18eac8678 0x18eac77d4 0x18e46ce5c 0x18e43de7c 0x18ed9330c 0x18ed95898 0x18ed8e7b0 0x184e2b77c 0x184e2b6fc 0x184e2af84 0x184e28b5c 0x184d48c58 0x186bf4f84 0x18e4a15c4 0x100eb5a20 0x18486856c) libc++abi.dylib:以 NSException 类型的未捕获异常终止

我是 Objective-C 和 iOS 的新手。我很有可能错过了一些简单/基本的东西。

这是创建按钮的代码:

for (int i =0 ; i < numDevices; i++)
{
    CBPeripheral* periph = devices[i];
    printf("%s%s\n", "Found Devices Name: ", [[periph name] UTF8String] );


    //Create button
    UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    [button addTarget:self  action:@selector(aMethod:) forControlEvents:UIControlEventTouchDown];
    [button setTitle:[periph name] forState:UIControlStateNormal];
    button.frame = CGRectMake(0, 0, 480, 100);

    //set constraints on button
    [button.heightAnchor constraintEqualToConstant:100].active = true;
    //[button.widthAnchor constraintEqualToConstant:210].active = true;

    //set image
    UIImageView* iv = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"App_Background.png"]];
    iv.frame = CGRectMake(0, 0, 480, 100);
    [button addSubview:iv];

    //Add action event to button
    [button addTarget:self action:@selector(Test:) forControlEvents:UIControlEventTouchUpInside];

    //add button to stackview
    [stackView addArrangedSubview:button];
}

这是点击按钮时应该调用的函数:

    -(IBAction) Test: (id) sender
{
    //printf("%s%s\n", "Selected Button: ", [[sender currentTitle] UTF8String]);
}

【问题讨论】:

    标签: ios objective-c user-interface button selector


    【解决方案1】:

    这是你的问题:

    [button addTarget:self  action:@selector(aMethod:) forControlEvents:UIControlEventTouchDown];
    

    这个按钮在self 上调用aMethod:,但是你还没有定义那个方法!删除该行应该可以解决问题。

    【讨论】:

    • 我注释掉了那行,但我仍然得到同样的错误。
    • 我建议做一个快速清理(Shift + Command + K)然后再试一次。这绝对是您收到该错误的原因。
    • 另外,您的 Test: 方法不需要 IBAction 返回类型。这仅适用于界面生成器,您不用于此按钮。
    • 天哪。我看错线了。我完全忘记了我在几个小时前添加了那条线。太感谢了。有时候多一双眼睛也不错。
    • 发生在我们所有人身上:)
    猜你喜欢
    • 2014-08-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-30
    • 1970-01-01
    • 2013-05-18
    • 2012-04-04
    • 1970-01-01
    相关资源
    最近更新 更多