Sunday, June 9, 2013

UINavigationController popToRootViewControllerAnimated example in Objective C (iOS).

UINavigationController popToRootViewControllerAnimated

Pops all the view controllers on the stack except the root view controller and updates the display.

- (NSArray *)popToRootViewControllerAnimated:(BOOL)animated

Set this value to YES to animate the transition. Pass NO if you are setting up a navigation controller before its view is displayed.

Return Value
An array of view controllers that are popped from the stack.

Discussion of [UINavigationController popToRootViewControllerAnimated]
The root view controller becomes the top view controller. For information on how the navigation bar is updated, see “Updating the Navigation Bar.”

UINavigationController popToRootViewControllerAnimated example.
Calling [self.navigationController popToRootViewControllerAnimated:YES] sets self.navigationController to nil. When you subsequently call [self.navigationController pushViewController:someOtherViewController] you are effectively sending a message to nil, which does nothing.

To workaround, simply set up a local reference to the navigationController and use that instead:

UINavigationController * navigationController = self.navigationController;
[navigationController popToRootViewControllerAnimated:NO];
[navigationController pushViewController:someOtherViewController animated:YES];

Example of [UINavigationController popToRootViewControllerAnimated].
[self dismissModalViewControllerAnimated:YES];
[self performSelector:@selector(patchSelector) withObject:nil afterDelay:0.3];

  [self.navigationController popToRootViewControllerAnimated:YES];

UINavigationController popToRootViewControllerAnimated example.
You can return to the first view with

[self.navigationController popToRootViewControllerAnimated:YES];
That being said, you can also remove a particular view controller, or navigate to a specific index in your view controller if you look at the example.

NSMutableArray *allViewControllers = [NSMutableArray arrayWithArray:navigationController.viewControllers];
// You can now manipulate this array with the methods used for NSMutableArray to find out / perform actions on the navigation stack  

[allViewControllers removeObjectIdenticalTo: removedViewController];
// You can remove a specific view controller with this.

navigationController.viewControllers = allViewControllers;

End of UINavigationController popToRootViewControllerAnimated example article.