WYS
WYS

Reputation: 1647

self.navigationItem.rightBarButtonItem doesn't work

Hi I have been doing a lot of research now, and used all of their solutions. I am kinda frustrated about this.

I have this in my viewDidLoad to create my rightbarbutton.

self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"bla"     style:UIBarButtonItemStyleBordered target:self action:@selector(test)];

Then I have this method test, for the selector.

- (void)test
{
NSLog(@"bla");
}

But somehow I always get unrecognized selector and it crashes everytime I press on the button, I even tried to make it with an argument, just to see if it works with a colon.

Upvotes: 1

Views: 1910

Answers (2)

Freddy
Freddy

Reputation: 2279

I had a similar issue..

1 - Make sure -(void)test is defined in your header.

2- If -(void)test isn't defined in your header then make sure it is implemented before you use it or make reference to it.

Also, If your not using ARC then your code above is going to leak.

Setting rightBarButtonItem retains the object (+1) and alloc/init (+1) meaning you will always have an extra reference count.

Try..

UIBarButtonItem *rbi = [[UIBarButtonItem alloc]initWithTitle:@"bla" style:UIBarButtonItemStyleBordered target:self action:@selector(test:)];
    self.navigationItem.rightBarButtonItem = rbi;
    [rbi release];

Upvotes: 0

Brandon A
Brandon A

Reputation: 926

Try defining the action like this:

-(void) test:(id)sender {
    NSLog(@"blah");
}

And in your button creation, use @selector(test:) instead.

This is the basic pattern for using the target/action pattern used throughout Cocoa. In some cases, you'll have multiple UI items calling the same action and you'll want to know which object triggered the action.

Upvotes: 1

Related Questions