iOS 在模式和导航 uiviewcontroller 中回到根 ViewController

iOS back to root ViewController in the modal and navigation uiviewcontroller

我有一个关于导航的结构,许多页面在 uiviewcontroller(UINavigationController) 上有模态(弹出)。

当我断开蓝牙时,我需要回root viewcontroller。

所以我在disconnect方法中设置了dismiss和popToRoot

 -(void) disconnect
 {
 ....
  [appDelegate.window.rootViewController dismissViewControllerAnimated:NO completion:nil];

  NSLog(@"appDelegate.window.rootViewController:%@",appDelegate.window.rootViewController.class);
 // show log appDelegate.window.rootViewController:UINavigationController

  [appDelegate.window.rootViewController.navigationController popToRootViewControllerAnimated:YES];
 ....
 }

但是当我运行程序和断开蓝牙时,

在案例 1 中:模态 viewcontroller 显示,

它将关闭模态viewcontroller,关闭是正确的。

但是在关闭模式后没有回到根导航控制器viewcontroller。

案例2:就在uinavigation controller页面。

当我断开蓝牙时,没有回到根导航控制器。

如何返回导航根页面?我的失败在哪里?

非常感谢。

// ------ 答案 ------

将代码更改为

  [appDelegate.window.rootViewController dismissViewControllerAnimated:NO completion:nil];

     [self performSelector:@selector(gotoRoot) withObject:nil afterDelay:0.50];

 - (void) gotoRoot {

     UINavigationController *myNavCon = (UINavigationController*)appDelegate.window.rootViewController;

     [myNavCon popToRootViewControllerAnimated:YES];
 }

从 class 开始,您展示了模态视图调用模态的关闭,然后在延迟一段时间后执行选择器,然后执行这里是示例代码

- (void) dismissAndGoToRoot {
      [self dismissViewControllerAnimated:YES completion:nil];
      [self performSelector:@selector(gotoRoot) withObject:nil afterDelay:0.50];
}

- (void)gotoRoot {

    [self.navigationController popToRootViewControllerAnimated:NO];
}

apple developer documentation 大约 dismissViewControllerAnimated:completion:

completion: The block to execute after the view controller is dismissed. This block has no return value and takes no parameters. You may specify nil for this parameter.

所以我认为这是更好的解决方案

[self dismissViewControllerAnimated:YES completion:^(){
    [self.navigationController popToRootViewControllerAnimated:NO];
}];

使用 completion 块优于 afterDelay。你如何选择好的延迟?如果太短会怎样?如果太长,执行代码什么都不等待...