2012-03-27 76 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 
} 

希望這有助於你。