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 ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access