按下按钮时无法识别的选择器

And*_*rew 4 iphone objective-c button ios

我简直不敢相信我在这么简单的事情上磕磕绊绊:

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {

        UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
        [button setTitle:@"Tap me" forState:UIControlStateNormal];
        [button addTarget:self action:@selector(test) forControlEvents:UIControlEventTouchUpInside];

        button.frame = CGRectMake(50, 50, 120, 60);
        [self.view addSubview:button];

    }
    return self;
}

-(void)test {
    NSLog(@"Test");
}
Run Code Online (Sandbox Code Playgroud)

当我按下按钮时发生unrecognized selector sent to instance错误,它会崩溃.

谁知道我在这里做错了什么?

编辑 - 错误消息:

-[__NSCFString test]: unrecognized selector sent to instance 0x29ee30
*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSCFString test]: unrecognized selector sent to instance 0x29ee30'
Run Code Online (Sandbox Code Playgroud)

编辑 - 如何呈现(ARC):

DemoViewController *demoVC = [[DemoViewController alloc] init];
    [self.window addSubview:demoVC.view];

    [self.window makeKeyAndVisible];
Run Code Online (Sandbox Code Playgroud)

Oma*_*ith 10

如果你正在使用ARC,那么demoVC.view将在函数结束后重新分配,而不是像这样初始化

DemoViewController *demoVC = [[DemoViewController alloc] init];
Run Code Online (Sandbox Code Playgroud)

在demoVC周围建立一个强大的属性并将其初始化为此

self.demoVC = [[DemoViewController alloc] init];
Run Code Online (Sandbox Code Playgroud)