单击我的按钮时,无法识别的选择器发送到实例错误

Unrecognized selector sent to instance error when I click my buttons

我花了一整天时间试图弄清楚为什么每当我单击代码中生成的一个按钮时都会收到此错误:

-[HomeViewController aMethod:]: unrecognized selector sent to instance 0x102813a00 * Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[HomeViewController aMethod:]: unrecognized selector sent to instance 0x102813a00' * First throw call stack: (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: terminating with uncaught exception of type NSException

我是 Objective-C 和 iOS 的新手。我很有可能遗漏了一些东西 simple/basic。

这是创建按钮的代码:

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

这是你的问题:

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

此按钮在 self 上调用 aMethod:,但您尚未定义该方法!删除该行应该可以解决问题。