Obj-C,只有iOS5可用时才有条件运行代码?

Jul*_*les 4 iphone cocoa-touch objective-c ios

如果iOS5可用,我如何检查并有条件地编译/运行代码?

mat*_*way 5

你可以检查这样的systemVersion属性UIDevice:

if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 5.0f) {
    // Do something
}
Run Code Online (Sandbox Code Playgroud)

但我个人不喜欢那种方法,因为我不喜欢从中返回的字符串的解析systemVersion和这样的比较.

最好的方法是检查你想要使用的类/方法是否存在.例如:

如果你想TWRequest在Twitter框架中使用:

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

或者,如果你想使用startMonitoringForRegion:CLLocationManager该被带到iOS中5.0:

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

一般来说,做这样的检查比查看系统版本更好.