iosuiviewcontrolleruinavigationcontrollerpoptoviewcontroller

[self.navigationController popToViewController:VC2 animated:NO]; crash


Hi I am developing an application in which I supposed to go:

  1. From UIViewController1 to UIViewController2
  2. From UIViewController2 to UIViewController3
  3. From UIViewController3 to UIViewController4
  4. From UIViewController4 back to UIViewController2

I am using UINavigationController. When I use [self.navigationController pushViewController:VC2 animated:NO]; and [self.navigationController popViewControllerAnimated:NO]; everything works fine.

But when I use [self.navigationController popToViewController:VC2 animated:NO]; from UIViewController4 application terminates saying Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Tried to pop to a view controller that doesn't exist.'

Following is my code how I am popping to UIViewController2

for (UIViewController *vc in self.navigationController.viewControllers) {
            if ([vc isKindOfClass:[ViewController2 class]]) {
                UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Main" bundle: nil];
                ViewController2 *VC2 = [storyboard instantiateViewControllerWithIdentifier:@"ViewController2"];
                [self.navigationController popToViewController:VC2 animated:NO];
            }
        }

When I printed navigation array it shows UIViewController2 in stack. I have added UINavigationController from Editor->embed in->Navigation Controller

Can anyone please tell me why this is happening? I tried to search for this issue but nothing is helpful


Solution

  • Here you instantiate a new VC2 view controller instance, this is not the instance you have on the navigation view controller stack!

    UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Main" bundle: nil];
                ViewController2 *VC2 = [storyboard     instantiateViewControllerWithIdentifier:@"ViewController2"];
    

    So you have to find the right instance in

    [[self.navigationController] viewControllers]
    

    Solution 1: (as iDev said, jump to second view controller on stack, use this if you know it is the second one)

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

    Solution 2: (generally go back 2 level on the stack)

    NSUInteger ownIndex = [self.navigationController.viewControllers indexOfObject:self];
    [self.navigationController popToViewController:[self.navigationController.viewControllers objectAtIndex:ownIndex - 2] animated:YES];