chilitechno.com
chilitechno.com

Reputation: 1575

UIBarButtonItem crashes iphone app when button is clicked

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.

Upvotes: 2

Views: 6053

Answers (3)

chilitechno.com
chilitechno.com

Reputation: 1575

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

Upvotes: 1

mmc
mmc

Reputation: 17404

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

Upvotes: 0

Daniel Dickison
Daniel Dickison

Reputation: 21882

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.

Upvotes: 0

Related Questions