Tips4-DisMiss Controller 到根控制器

在项目中遇到过这种情况:A控制器presentB控制器,B控制器presentC控制器,然后C控制器需要直接dismiss到A控制器。
解决这个问题需要了解Controller的两个只读属性:presentedViewContrller和presentingViewController。它们所代表的含义是:被present的控制器和正在presenting的控制器。
For Example:

1
[A presentViewContrller:B animated: YES completion: nil];

对于控制器A和B,A相对于B来说就是正在presenting的控制器,B相对于A来说是presented的控制器,亦即, B.presentingViewContrller能拿到A控制器,A.presentedViewController能拿到B控制器。
了解了这两个概念后,我们怎么写从C控制器dismiss到A控制器呢?
我们可以在C控制器的返回方法里这么写:

1
2
3
4
5
UIViewController *rootVC = self.presentingViewController;
while (rootVC.presentingViewController) {
rootVC = rootVC.presentingViewController;
}
[rootVC dismissViewControllerAnimated:YES completion:nil];