Search code examples
objective-cxcodexcode4

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.


Solution

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