30

I have a button named 'HOME'. In that button action I have the following code:

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

When I click this button my app crashes.

Changing the index from 1 to 2, then it pops the view perfectly.

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

My view sequence is Page1 --> Page2 --> Page3

I want to go from Page3 to Page1 but the app crashes. From Page3 to Page2 it works fine.

Neil Masson
  • 2,609
  • 1
  • 15
  • 23
Sam007
  • 1,385
  • 3
  • 17
  • 32

4 Answers4

86

Try this.

Where I have written SeeMyScoresViewController you should write your View Controller class on which you have to go.(eg. Class of Home)

NSArray *viewControllers = [[self navigationController] viewControllers];
for( int i=0;i<[viewControllers count];i++){
    id obj=[viewControllers objectAtIndex:i];
    if([obj isKindOfClass:[SeeMyScoresViewController class]]){
        [[self navigationController] popToViewController:obj animated:YES];
        return;
    }
}
galuszkak
  • 513
  • 4
  • 25
Gypsa
  • 11,230
  • 6
  • 44
  • 82
  • this make my app crash next time I click on the back button (on the SeeMyScoresViewController) – Lucas Apr 20 '13 at 19:29
21

If you want to go to the root viewcontroller (page1) just use:

    [self.navigationController popToRootViewControllerAnimated:YES];

Also the first item in an index is not item 1 but item 0:

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

This should bring you back to the first viewController, but it will them be easier to use the popToRootViewController method.

rckoenes
  • 69,092
  • 8
  • 134
  • 166
  • hey @rckoenes can you please reply to this similar question - http://stackoverflow.com/questions/32546217/proper-way-to-call-poptoviewcontroller-ios – Tariq Sep 13 '15 at 04:58
3

Often it is more important to do that from top of stack, so:

In UINavigationController subclass or category:

- (void)popToLast:(Class)aClass
{
    for (int i=self.viewControllers.count-1; i>=0; i--)
    {
        UIViewController *vc = self.viewControllers[i];
        if ([vc isKindOfClass:aClass])
        {
            [self popToViewController:vc animated:YES];
            break;
        }
    }
}

and you call that

popToLast:[SomeViewController class];
Leszek Zarna
  • 3,253
  • 26
  • 26
1

An up-to-date way of popping back to a specific controller is:

[self.navigationController.viewControllers enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {

    if ([obj isKindOfClass:[MyViewController class]]) {
        [self.navigationController popToViewController:obj animated:YES];
        *stop = YES;
    }
}];

MyViewController is the controller you want to pop back to.

isair
  • 1,790
  • 15
  • 15