Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unrecognised selector on button press

I can't believe i'm stumbling on something so simple:

- (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");
}

It crashes when I press the button, with an unrecognized selector sent to instance error.

Anybody know what I could be doing wrong here?

Edit - error message:

-[__NSCFString test]: unrecognized selector sent to instance 0x29ee30
*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSCFString test]: unrecognized selector sent to instance 0x29ee30'

Edit - how it's presented (ARC):

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

    [self.window makeKeyAndVisible];
like image 676
Andrew Avatar asked Dec 27 '22 22:12

Andrew


1 Answers

If you are using ARC, then demoVC.view will be realeasd just after the function ends, instead of just initializing like this

DemoViewController *demoVC = [[DemoViewController alloc] init];

Make a strong property around demoVC and initialize it as this

self.demoVC = [[DemoViewController alloc] init];
like image 119
Omar Abdelhafith Avatar answered Jan 15 '23 20:01

Omar Abdelhafith