While working on my first iphone project, on later stage i had a requirement to manipulate my navigation controller stack of my app. I’ll explain what i mean by manipulating ? My app consists of various screens, with it comes navigation between them. So for instance lets say “A” is the initial first screen or to be more precise first view controller inside navigation controller. Now from “A”, i navigate to “B” then “C” and finally “D”. On screen “D” i wanted to pop my current view controller i.e pop “D” from navigation stack. It is simple to do that, just call popViewControllerAnimated to pop “D”. Popping “D” would lead me to “C” and its natural since “C” is below “D” on the stack. But i wanted to navigate to “B” instead of “C” and also pop “C” when i pop “D” explicitly. This is what i am talking about manipulating navigation stack. So how do you this ?

I found that navigation stack is maintained in array. You can manipulate the array and assign that array to navigation controller, whole navigation stack of your app is defined by this array then. Here is the code:

NSMutableArray *allControllers = [[NSMutableArray alloc] initWithArray:self.navigationController.viewControllers];
        
NSArray *allControllersCopy = [allControllers copy];
        
for (id object in allControllersCopy) {
      if ([object isKindOfClass:[MyC class]])
                [allControllers removeObject:object];
}
        
[allControllersCopy release];
        
[self.navigationController setViewControllers:allControllers animated:NO];
[allControllers release];

I am getting array of view controllers within navigation stack. Next i am iterating through it and checking if a viewcontroller is “C”, if it is then i am simply removing it from array. Now i assign array back to navigation controller. After that simply popping my current view controller “D”.

[self.navigationController popViewControllerAnimated:YES];

Well it worked for me, and i am using it whenever such needs arise.

Thanks.