How to pop a UINavigationController in code

In UINavigationController speak, we “push” new controllers onto the stack (go forward), and we “pop” them off the stack (go back). The navigation controller handles all this for us.

If you want to go back exactly one view controller, here’s how you can do it programmatically:

    // pop back to previous controller
    NSArray *myControllers = self.navigationController.viewControllers;
    int previous = myControllers.count - 2;
    UIViewController *previousController = [myControllers objectAtIndex:previous];
    
    [self.navigationController popToViewController:previousController animated:YES];

First we access the array of all view controllers and count it. We subtract one (because arrays are 0 based), and another one to go back in history – hence we go “minus 2″. Then we pop to view controller just behind the current one.

Test if the returned value is less than zero though…

If you want to go back all the way to the root view controller, there’s a method for that:

    // pop back to root controller
    [self.navigationController popToRootViewControllerAnimated:YES];




Jay is the CEO and founder of WP Hosting, a boutique style managed WordPress hosting and support service. He has been working with Plesk since version 9 and is a qualified Parallels Automation Professional. In his spare time he likes to develop iOS apps and WordPress plugins, or draw on tablet devices. He blogs about his coding journey at http://wpguru.co.uk and http://pinkstone.co.uk.