Andrew
Andrew

Reputation: 16051

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

Upvotes: 4

Views: 798

Answers (4)

Luavis
Luavis

Reputation: 49

when adding any UI Component with code it need to add in viewDidLoad or loadView(if you don`t add xib file) override method.

and also you need to add parameter for sender (this is recommandation)

ex ) - (void)test:(id)sender

and add target like this.... [button addTarget:self action:@selector(test:) forControlEvents:UIControlEventTouchUpInside]

Upvotes: -1

Jesse Rusak
Jesse Rusak

Reputation: 57168

Your error message indicates (most likely) that your view controller is being deallocated before the button is pushed. (It shows that the message is being sent to an NSString, which is probably occupying the memory that the view controller used to be at.)

The easiest way to hunt this down is to use zombies to confirm this and identify why your object is being deallocated early.

EDIT: Based on your presentation code, you should make, for example, an instance variable to keep a reference to your view controller. You probably also want to move your button initialization code to viewDidLoad to avoid other problems in the future. (Or just hook up the button in a nib!)

Upvotes: 3

Mehdzor
Mehdzor

Reputation: 799

You might calling "test" method for NSString somewhere in your code.

Upvotes: -2

Omar Abdelhafith
Omar Abdelhafith

Reputation: 21221

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

Upvotes: 10

Related Questions