在iOS 5应用中条件性支持iOS 6功能

7

如果一个应用的Minimal Deployment Target设置为iOS 5.0,如何支持iOS6的功能呢?

例如,如果用户使用的是iOS 5,他将看到一个UIActionSheet,如果用户使用的是iOS 6,则会看到一个不同的UIActionSheet。你该如何实现这一点呢?我使用的是Xcode 4.5,想要在iOS 5上运行应用。

1个回答

19
您应该优先检测可用的方法/功能,而不是检测iOS版本并假设某个方法可用。
请参见苹果文档
例如,在iOS 5中显示模态视图控制器,我们可以这样做:
[self presentModalViewController:viewController animated:YES];

在iOS 6中,UIViewControllerpresentModalViewController:animated:方法已被弃用,你应该在iOS 6中使用presentViewController:animated:completion:。但是,你如何知道什么时候使用哪个方法呢?
你可以检测iOS版本并使用if语句来决定使用前者还是后者,但这很脆弱,你可能会犯错,也许将来的新操作系统会有一种新的方法来解决这个问题。
正确处理此问题的方法是:
if([self respondsToSelector:@selector(presentViewController:animated:completion:)])
    [self presentViewController:viewController animated:YES completion:^{/* done */}];
else
    [self presentModalViewController:viewController animated:YES];

你甚至可以认为你应该更加严格,采取以下措施:
if([self respondsToSelector:@selector(presentViewController:animated:completion:)])
    [self presentViewController:viewController animated:YES completion:^{/* done */}];
else if([self respondsToSelector:@selector(presentViewController:animated:)])
    [self presentModalViewController:viewController animated:YES];
else
    NSLog(@"Oooops, what system is this !!! - should never see this !");

我对你的 UIActionSheet 示例不确定,据我所知,在iOS 5和6上是相同的。也许你在想分享时使用 UIActivityViewController,如果你在iOS 5上需要回退到 UIActionSheet,那么你需要检查一个类是否可用,可以参考 这里 的方法。

您可以在项目设置中链接框架,如果框架不在所有版本中都存在,就像您的情况一样,您只需将包含设置为可选而不是必需即可。 - Daniel
@Daniel:如何知道使用respondsToSelector的方法?或者每次都需要这样做吗? - user2568508
respondsToSelector:会检查接收者上传递给它的方法是否可用。因此,通常您会在要调用的方法上调用此方法。有时,您会调用多个属于同一iOS版本/规范的方法,因此检查一个方法就可以假定其他方法也可用。 - Daniel

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接