Saturday, June 8, 2013

UINavigationController viewControllers example in Objective C (iOS).

UINavigationController viewControllers

The view controllers currently on the navigation stack.

@property(nonatomic, copy) NSArray *viewControllers

Discussion of [UINavigationController viewControllers]
The root view controller is at index 0 in the array, the back view controller is at index n-2, and the top controller is at index n-1, where n is the number of items in the array.

Assigning a new array of view controllers to this property is equivalent to calling the setViewControllers:animated: method with the animated parameter set to NO.

UINavigationController viewControllers example.
UINavigationControllers have a property called viewControllers as you have stated above. Since this is an array of View Controllers, referencing a specific view controller in this hierarchy is no different than accessing any other object in an array.

UIViewController *theControllerYouWant = [self.navigationController.viewControllers objectAtIndex:(theIndexOfYourViewController)];
In addition check out the View Controller's Programming Guide for iOS specifically the section called 'Modifying the Navigation Stack'.

Example of [UINavigationController viewControllers].
NSMutableArray *array = [[NSMutableArray alloc] initWithArray:self.navigationController.viewControllers];
[array removeObjectAtIndex:1];

self.navigationController.viewControllers = array;
Or just use

[self.navigationController setViewControllers:array animated:NO];

UINavigationController viewControllers example.
Pretty Simple, when about to push the thirdViewController inseat of doing a simple pushViewController do this:

NSArray * viewControllers = [self.navigationController viewControllers];
NSArray * newViewControllers = [NSArray arrayWithObjects:[viewControllers objectAtIndex:0], [viewControllers objectAtIndex:1], thirdController,nil];
[self.navigationController setViewControllers:newViewControllers];
where [viewControllers objectAtIndex:0] and [viewControllers objectAtIndex:1] are your rootViewController and your FirstViewController.

End of UINavigationController viewControllers example article.