tags:

views:

1409

answers:

1

I've got a UINavigationController with a series of UIViewControllers on it. Under some circumstances, I want to pop back exactly two levels. I thought I could do it by calling popViewControllerAnimated twice in a row, but it turns out that the second time I call it, it's not popping anything and instead returning NULL. Do I need to store a reference to my destination VC and call popToViewControllerAnimated instead? I can do that, but it complicates my code since I'd have to pass the UIViewController* around as I'm pushing VCs onto the stack.

Here's the relevant snippet:

UIViewController* one = [self.navigationController popViewControllerAnimated:YES];
if (...) {
    // pop twice if we were doing XYZ
    UIViewController *two = [self.navigationController popViewControllerAnimated:YES];
    // stored in "one" and "two" for debugging, "two" is always 0 here.
}

Am I doing something weird here? I want to write idiomatic code, so if the "right" way is to call popToViewControllerAnimated, or something else entirely, I'll happily change it.

Thanks much! -Mike

+3  A: 

In this case you would need to pop back to a specific viewcontroller in the navigationController like so:

[self.navigationController popToViewController:[[self.navigationController viewControllers] objectAtIndex:2] animated:YES];

That code would pop to the third viewcontroller on the navigationController's stack.

Programasaurus
oooh, I think I can make that work for me without having to pass the ViewController pointers around. Thanks!
Mike Kale
As an FYI, I had to use the viewControllers.count - 3 to go two back. vc.count - 1 is the top view, and two back from there is -3.
Mike Kale
Perfect! You even knew that I wanted to pop to 3rd viewcontroller - all I had to do was cut and paste. Thanks.
Smendrick