Unrecognized selector when a button is pressed

I canโ€™t believe that I am tripping on something very 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"); } 

Failed to click a button with an error unrecognized selector sent to instance .

Does anyone know what I can do 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 is presented (ARC):

 DemoViewController *demoVC = [[DemoViewController alloc] init]; [self.window addSubview:demoVC.view]; [self.window makeKeyAndVisible]; 
+4
source share
4 answers

If you use ARC, demoVC.view will be realeasd right after the function finishes, and not just initialization like this

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

Create a strong property around demoVC and initialize it as

 self.demoVC = [[DemoViewController alloc] init]; 
+10
source

Your error message indicates (most likely) that your view controller is freed before the button is clicked. (It shows that the message is being sent to NSString, which probably takes up the memory that the view controller used to be on.)

The easiest way to look for this is to use zombies to confirm this and determine why your object is being freed earlier.

EDIT: based on your presentation code, you should make, for example, an instance variable in order to maintain a link to your view controller. You probably also want to translate the button initialization code to viewDidLoad to avoid other problems in the future. (Or just plug in the button at the tip!)

+3
source

when adding any component of the user interface with code that needs to be added to the viewDidLoad or loadView method (if you do not add the xib file).

and also you need to add a parameter for the sender (this is a recommendation)

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

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

-1
source

You can call the "test" method for NSString somewhere in your code.

-2
source

All Articles