O'Reilly logo

iOS 5 Programming Cookbook by Vandad Nahavandipoor

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

2.9. Manipulating a Navigation Controller’s Array of View Controllers

Problem

You would like to directly manipulate the array of view controllers associated with a specific navigation controller.

Solution

Use the viewControllers property of the UINavigationController class to access and modify the array of view controllers associated with a navigation controller:

- (void) goBack{
  /* Get the current array of View Controllers */
  NSArray *currentControllers = self.navigationController.viewControllers;

  /* Create a mutable array out of this array */
  NSMutableArray *newControllers = [NSMutableArray
                                    arrayWithArray:currentControllers];

  /* Remove the last object from the array */
  [newControllers removeLastObject];

  /* Assign this array to the Navigation Controller */
  self.navigationController.viewControllers = newControllers
}

You can call this method inside any view controller in order to pop the last view controller from the hierarchy of the navigation controller associated with the current view controller.

Discussion

An instance of the UINavigationController class holds an array of UIViewController objects. After retrieving this array, you can manipulate it in any way you wish. For instance, you can remove a view controller from an arbitrary place in the array.

Manipulating the view controllers of a navigation controller directly by assigning an array to the viewControllers property of the navigation controller will commit the operation without a transition/animation. If you wish this operation ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required