-[UINavigationController popToViewController:transition:]

时间:2018-10-31 03:07:00

标签: ios objective-c uikit

最近,我遇到了一个问题:

- (void)popToVC {
    FirstViewController *f1 = [FirstViewController new];
    f1.text = @"1111111";
    SecondViewController *f2 = [SecondViewController new];
    f2.text = @"2222222";
    ThirdViewController *f3 = [ThirdViewController new];
    f3.text = @"3333333";
    FirstViewController *f4 = [FirstViewController new];
    f4.text = @"4444444";
    FirstViewController *f5 = [FirstViewController new];
    f5.text = @"5555555";
    FirstViewController *f6 = [FirstViewController new];
    f6.text = @"6666666";
    [f2 addChildViewController:f3];
    [f2 addChildViewController:f4];
    [f2.view addSubview:f3.view];
    [self.navigationController pushViewController:f1 animated:YES];
    [self.navigationController pushViewController:f2 animated:YES];
    [self.navigationController pushViewController:f5 animated:YES];
    [self.navigationController pushViewController:f6 animated:YES];
    // [self.navigationController popToViewController:f3 animated:YES];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self.navigationController popToViewController:f3 animated:YES];
    });
}

执行此代码时,出现如下异常:

  

***由于未捕获的异常“ NSInternalInconsistencyException”而终止应用程序,原因:“试图弹出到不存在的视图控制器。”

如果我取消注释[self.navigationController popToViewController:f3 animated:YES];并删除下一行代码dispatch_after,则什么也没有发生。

为什么当我将[self.navigationController popToViewController:f3 animated:YES];写入dispatch_after时,代码崩溃了,如果我不使用dispatch_after也不会崩溃?

1 个答案:

答案 0 :(得分:0)

这取决于推入和弹出顺序是批处理操作。只要第一个操作成功,其余的错误都会被传递。

// [self.navigationController popToViewController:f3 animated:YES];
[self.navigationController pushViewController:f1 animated:YES];
[self.navigationController pushViewController:f2 animated:YES];
[self.navigationController pushViewController:f5 animated:YES];
[self.navigationController pushViewController:f6 animated:YES];

现在取消注释第一行,将产生错误。但是,如果第一行在操作结束时,则什么也没有发生。同样,

 dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
   // [self.navigationController popToViewController:f5  animated:YES];
    [self.navigationController popToViewController:f3 animated:YES];
});

取消注释第一行不会带来任何问题,只要成功执行了第一项操作即可。

一个极端的例子如下所示。

[self.navigationController pushViewController:f1 animated:YES];
[self.navigationController pushViewController:f2 animated:YES];
[self.navigationController popToViewController:f5 animated:YES];
[self.navigationController popToViewController:f6 animated:YES];
[self.navigationController popToViewController:f3 animated:YES];

dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
  [self.navigationController popToViewController:f1  animated:YES];
  [self.navigationController popToViewController:f3 animated:YES];
  [self.navigationController popToViewController:f6 animated:YES];

});

希望这是答案。