Search code examples
iphoneiosuibuttonunrecognized-selectormethod-invocation

Unrecognized Selector Sent To Instance, iPhone Error


I get the error

"012-02-10 13:54:52.570 HelloWorld[14275:10103] -[HelloWorldViewController buttonPressed]: unrecognized selector sent to instance 0x6cc0c50 2012-02-10 13:54:52.572 HelloWorld[14275:10103] * Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[HelloWorldViewController buttonPressed]: unrecognized selector sent to instance 0x6cc0c50'".

This is the offending text:

-(void)buttonPressed:(id)sender {
    UIButton *button = (UIButton*)sender;
    NSString *text = [button titleForState:UIControlStateNormal];
    NSLog(@"%@",text);
}

I know this because if I change the code to this:

-(void)buttonPressed {
    NSLog(@"Button Pressed");
}

It then works correctly.

However I need the text from the component that sent the message. The components are not drag and dropped with IB. They are allocated, initialized and placed in the loadView method. To each of my buttons I have added buttonPressed as the action listener.


Solution

  • The error unrecognized-selector could be due to a missing :.

    [yourbutton addTarget:self action:@selector(buttonPressed:) forControlEvents:UIControlEventTouchUpInside];
    

    instead of

    [yourbutton addTarget:self action:@selector(buttonPressed) forControlEvents:UIControlEventTouchUpInside];
    

    In the first case you call -(void)buttonPressed:(id)sender. In the second instead you call -(void)buttonPressed.

    But if you provide more code for your UIButton, it could be simpler to understand what is going on.