多级presentModalViewController处理

来源:互联网 发布:微电影剪辑软件 编辑:程序博客网 时间:2024/05/01 00:36

我们都知道使用弹出模态视图时有两个重要的函数presentModalViewController和dismissModalViewControllerAnimated,前面一个函数相信大家使用起来都没有问题,我想说的是后面这个函数dismissModalViewControllerAnimated,通过字面我们可以看出它的意思就是使弹出视图消失。我们设A弹出B,那么A就是presenting一方,B就是presented一方。那么该由谁来调用这个方法呢,是弹出的一方,还是被弹出的那一方呢,为此找到官方文档中如下解释:

The presenting view controller is responsible for dismissing the view controller it presented. If you call this method on the presented view controller itself, however, it automatically forwards the message to the presenting view controller.

  通过解释我们可以看出,presenting一方是负责让弹出模态视图消失的,但是系统在此处帮我们做了一个遍历就是当我们在被弹出一方调用该函数时候,系统会自动把这个消息传递到弹出它的那个VC中。

  下面我们在思考个问题,如果A弹出B,B又弹出C,此时我们通过B调用dismissModalViewControllerAnimated方法,到底是只有C被dismiss还是B和C一起被dismiss呢?

  我写了一个小程序验证了一下,程序如下:

复制代码
 1 - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions 2 { 3     self.window = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease]; 4     // Override point for customization after application launch. 5     _svVCA = [[SvViewController alloc] initWithNibName:nil bundle:nil]; 6     self.viewController = [[[UINavigationController alloc] initWithRootViewController:_svVCA] autorelease]; 7     [_svVCA release]; 8     _svVCA.view.backgroundColor = [UIColor clearColor]; 9     _svVCA.contentStr = @"A";10     11     self.window.rootViewController = self.viewController;    12     [self.window makeKeyAndVisible];13     14     _svVCB = [[SvViewController alloc] init];15     _svVCB.contentStr = @"B";16     [_svVCA presentModalViewController:_svVCB animated:NO];17     [_svVCB release];18     19     _svVCC = [[SvViewController alloc] init];20     _svVCC.contentStr = @"C";21     [_svVCB presentModalViewController:_svVCC animated:NO];22     [_svVCC release];23     24     [_svVCB dismissModalViewControllerAnimated:NO];25     //[_svVCB dismissModalViewControllerAnimated:NO];26     27     return YES;28 }
复制代码

  上面程序中我们可以看出,一开始我们创建一个A,然后添加到window中,然后弹出B,B在弹出C,接着我们就调用[_svVCB dismissModalViewControllerAnimated:NO];

  运行结果如下:

    

  上图中最左边的图是没有调用任何dismiss的情况下的结果,中间这幅图是通过B调用一次dismissModalViewControllerAnimated的结果,右边的图是连着通过B调用两次dismissModalViewControllerAnimated的结果。

  通过程序测试我们可以发现当一个VC即是被弹出方(被A弹出),也是弹出方(弹出C)的时候,调用dismiss的时候是直接将其弹出的VC消失掉,而不是传递该消息到弹出它的VC去,只有当该VC没有弹出别的VC的时候才会传递消息到弹出它的VC去。这块儿可能说的有点儿绕,简单的说就是无私原则,就是B已经占了资源了,当接到释放命令的时候,就必须的先交出自己的,自己没有占有资源的时候才能尝试向上一级发出申请。










http://www.cnblogs.com/smileEvday/archive/2012/10/14/PresentModalViewController2.html