今天用模态视图控制器(Modal View Controller)时遇到了一个很狗血的问题,按理说presentModalViewController和dismissModalViewControllerAnimated应该成对出现,一般情况下presentModalViewController会在parentViewController被直接调用,用来弹出一个新视图;而dismissModalViewControllerAnimated则一般在childViewController用来dismiss自己,它的原理是将dismiss消息转发给了parentViewController进行dismiss,问题就在怎将dismiss消息转发给parentViewController,以前我一直以为是
[self.parentViewController dismissModalViewControllerAnimated:YES];
之前在(Xcode4.0)模拟器(iphone 4.3)上跑了也没问题,今天换了台mac(Xcode4.2)上机器(IOS5)时却发现不管用了,赶紧查资料,果然是系统版本问题:
[self.parentViewController dismissModalViewControllerAnimated:YES]; (ios5前) [self.presentingViewController dismissModalViewControllerAnimated:YES]; (ios5后)
于是回自己机器(Xcode4.0)试着改为
[self.presentingViewController dismissModalViewControllerAnimated:YES];
结果Xcode(4.0)直接报错,说找不着presentingViewController,改为
[[self presentingViewController] dismissModalViewControllerAnimated:YES];
警告可能不响应presentingViewController,不管了,先在模拟器(iphone 4.3)上跑,发现不行(Xcode4.0没有iphone 5.0模拟器)!赶紧换到Xcode4.2的那个机器,跑iphone 5.0模拟器发现可以,连警告都没有,可是一跑iphone 4.3模拟器又悲剧了,这让人情何以堪,无奈我只能调用前先判断一下:
if ([self respondsToSelector:@selector(presentingViewController)]) { [[self presentingViewController] dismissModalViewControllerAnimated:YES]; } else { [[self parentViewController] dismissModalViewControllerAnimated:YES]; }
跑了一下,发现两个模拟器总算不蹦了,上机器两个也算都正常了。最终完美的方案是使用Xcode 4.2代码写成:
if ([self respondsToSelector:@selector(presentingViewController)]) { [[self presentingViewController] dismissModalViewControllerAnimated:YES]; } else { [[self parentViewController] dismissModalViewControllerAnimated:YES]; }