Iphone – How to call a method when back button on a UINavigationController is pressed? (iPhone)

ipadiphoneuinavigationcontroller

How can I call a method when the back button on a UINavigationController is pressed. I need to be able to call a method before the previous view is displayed. Is this possible? If so please can someone advise on how to do this?

Best Answer

A fast solution is to add an implementation for the viewWillDisappear: method. It will be triggered as soon as the viewController will disappear in response to the back button pression.

- (void)viewWillDisappear:(BOOL)animated {
  //... 
  //make you stuff here
  //... 
}

Another solution is to add a custom responder to the back button. You can modify your viewController's init method as follow:

- (id)init {
    if (self = [super init]) {
        //other your stuff goes here
        //... 
        //here we customize the target and action for the backBarButtonItem
        //every navigationController has one of this item automatically configured to pop back
        self.navigationItem.backBarButtonItem.target = self;
        self.navigationItem.backBarButtonItem.action = @selector(backButtonDidPressed:);
    }
    return self;
}

and then you can use a selector method as the following. Be sure to dismiss correctly the viewController, otherwise your navigation controller won't pop as wanted.

- (void)backButtonDidPressed:(id)aResponder {
    //do your stuff
    //but don't forget to dismiss the viewcontroller
    [self.navigationController popViewControllerAnimated:TRUE];
}