Question

UIBarButtonItem *rButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemRefresh target:self action:NULL];

rButton.action = @selector(refreshAction);
self.navigationItem.rightBarButtonItem = rButton;
[rButton release];

The above code works fine to create a button and add it to the navigation bar, but when I click on the button it crashes the app with a EXC_BAD_ACCESS. If I comment out rButton.action = @selector(refreshAction); clicking the button won't do anything but it doesn't crash either.

- (void)refreshAction {
    NSLog(@"refreshAction");
}

This code is in a TableViewController's viewDidLoad method which is pushed onto the navigationController stack from the NavigationViewController viewDidLoad method.

I've spent probably 3 hours trying to get this to work, to no avail.

Was it helpful?

Solution

As usual memory management was the culprit. Loading the tableViewController from the navigationController:

NearbyTableViewController *tableController = [[[NearbyTableViewController alloc] initWithNibName:@"NearbyTableViewController" bundle:nil] autorelease];
self.nearbyTableController = tableController;   

[self pushViewController:self.nearbyTableController animated:YES];
[tableController release];

releasing an object set to autorelease... must be the most common error in memory management. Deleting that line [tableController release] solved the problem

OTHER TIPS

Any luck if you specify @selector(refreshAction) when you create the button, i.e.:

UIBarButtonItem *rButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemRefresh target:self action:@selector(refreshAction)];

Maybe the target doesn't get saved if you don't also specify the action to the initializer.

I'm not exactly 100% sure why your code does not work, but setting the selector directly in the constructor does work:

UIBarButtonItem *rButton = [[UIBarButtonItem alloc] 
    initWithBarButtonSystemItem:UIBarButtonSystemItemRefresh   
                         target:self 
                         action:@selector(refreshAction)];
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top