2012-03-27 75 views
4

如何在iOS5可用时检查并有条件地仅编译/运行代码?Obj-C,只有iOS5可用时才有条件运行代码?

+4

你不希望有条件地编译代码,否则,将只编译基于你有你的编译机器上的,然后如果你的iOS5的设备上运行的代码将无法使用的代码。 – 2012-03-27 08:20:26

+0

看看[检查iPhone的iOS版本](http://stackoverflow.com/questions/3339722/check-iphone-ios-version) – 2012-03-27 08:25:22

回答

5

您可以检查的systemVersion属性,像这样:

if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 5.0f) { 
    // Do something 
} 

但我个人不喜欢这样的方法,我不喜欢从systemVersion返回的字符串的分析和比较完成像那样。

,最好的办法是检查任何类/方法是要使用,存在。例如:

如果你想使用TWRequest来自Twitter的框架:

Class twRequestClass = NSClassFromString(@"TWRequest"); 
if (twRequestClass != nil) { 
    // The class exists, so we can use it 
} else { 
    // The class doesn't exist 
} 

或者,如果你想使用CLLocationManagerstartMonitoringForRegion:这是带来了在IOS 5.0:

CLLocationManager *locationManager = [[CLLocationManager alloc] init]; 
... 
if ([locationManager respondsToSelector:@selector(startMonitoringForRegion:)]) { 
    // Yep, it responds 
} else { 
    // Nope, doesn't respond 
} 

在一般最好做这样的检查,而不是查看系统版本。

4

试试这个代码:

if([[[UIDevice currentDevice] systemVersion] floatValue] >= 5.0) 
{ 
    //Do stuff for iOS 5.0 
} 

希望这有助于你。