Ready to Level-Up?

This just in! If your rusty iOS skills could use some refining, or if you're just starting out and you want to level-up fast, consider signing up for our upcoming iOS Screencasts

New from iOS Rocket Surgery Swift Video Tutorials: The rapidly evolving Apple-iOS ecosystem has just been thrown into tumult with the recent introduction of the Swift Programming Language. Are you ready to finally try iOS development? Are you needing to switch from Objective-C to Swift? Sign up today for our free video courses!
(By the dear folks at Swift Tutorial Videos, a sister company)

Tuesday, December 17, 2013

iOS Pop to a Specific View Controller

So, you're in a NavigationController hierarchy, and you want to pop to a specific view controller in the hierarchy, huh?

Lets say you're in a NavigationController hierarchy, so views have been pushed one on top of the other, and you find yourself several layers deep in the view stack. How would one, for example, pop to the bottom element in the stack, or more interestingly, to the ViewController above the bottom view in the stack?

Here's a quick example for doing that:

  [self popToViewController:[self.viewControllers objectAtIndex:1] animated:animated];

But, that's not exactly what you're after, is it? You want to know how to pop to a specific view in the view stack, lets say, from the context of a ViewController and given its class name. We'll, heres how you can do that:

-(void)popToViewControllerWithClassName:(NSString *)viewControllerClassName
  Class targetClass = NSClassFromString(viewControllerClassName);

  // We're in a view controller in a navigation controller hierarchy, so we can just
  // get my UINavigationController thusly:
  UINavigationController *navigationController = self.navigationController;

  // Iterate over the list of viewcontrollers in this navigation hierarchy
  int indx = 0;
  for(UIViewController *viewController in navigationController.viewControllers){
    if([viewController isMemberOfClass:targetClass]){
  [self popToViewController:[self.viewControllers objectAtIndex:indx] animated:YES];

In brief, it creates a Class from the name you provide, gets the NavigationController, and iterates over the view stack until it finds the correct class... then it pops to that view in the stack. On the plus side, if the view is not found in the stack, the view will not pop (since its is effectively popping back to the current view).

If you found this helpful and think you might need this page again in the future, why not give it a +1, and we'll show up at the top of your search results.

Good luck on your journey!

About Me

Easy NSDateFormatter Tool

Save yourself some time in formatting your NSDates to NSStrings, and use the Blind NSDate app, which you can download from iTunes. There's also a website where you can format your NSDates:

Popular Posts

Designed By Seo Blogger Templates