如何在不破坏应用程序的情况下仅针对iOS 5执行代码

Jim*_*mmy 2 iphone xcode objective-c ios5

如何仅针对iOS 5兼容性的iOS 5执行代码?我写了这段代码:

 BOOL isIOS5 = [[[UIDevice currentDevice] systemVersion] floatValue] > 4.3;
 if (isIOS5) {

    [[UINavigationBar appearance]setBackgroundImage:[UIImage imageNamed:@"cabecera.png"] forBarMetrics:UIBarMetricsDefault];
    [[UINavigationBar appearance]setTintColor:[UIColor colorWithRed:80.0f/255.0f green:150.0f/255.0f blue:185.0f/255.0f alpha:1]];

 }
Run Code Online (Sandbox Code Playgroud)

如果我在iOS 5中执行该应用程序它工作正常,但如果我尝试在iOS <5模拟器中执行该应用程序,它会中断.有没有办法编写一个只有iOS5代码但在iOS <5时忽略它的应用程序?

Dan*_*iel 9

在您的情况下,您应该检查当前iOS版本中该方法是否可用:

if([UINavigationBar respondsToSelector:@selector(appearance)]) //iOS >=5.0
{
    [[UINavigationBar appearance]setBackgroundImage:[UIImage imageNamed:@"cabecera.png"] forBarMetrics:UIBarMetricsDefault];
    [[UINavigationBar appearance]setTintColor:[UIColor colorWithRed:80.0f/255.0f green:150.0f/255.0f blue:185.0f/255.0f alpha:1]];
}
Run Code Online (Sandbox Code Playgroud)

还请看这个问题/答案.


Ali*_*are 6

您不应该测试操作系统的版本.

相反,您应该测试该功能是否可用.

特别是测试UINavigationBar是否响应@selector(appearance)选择器.

你应该阅读这篇解释它的Apple文档(尤其是这个页面)