Objective C 没有 可用性检查 作为语言的一部分,因为通过 Objective C 预处理器可以获得相同的结果。
这是 C 派生语言的“传统”方式。
想知道是否在调试模式下编译?
#ifdef DEBUG
// code which will be inserted only if compiled in debug mode
#endif
想在编译时检查最低版本吗?
在 iOS 中使用 Availability.h 标头,在 Mac OS X 中使用类似标头。
此文件位于 /usr/include 目录中。
只需使用预处理器测试 __IPHONE_OS_VERSION_MAX_ALLOWED,例如:
#if __IPHONE_OS_VERSION_MAX_ALLOWED >= 80000
if ([application respondsToSelector:@selector(registerUserNotificationSettings:)]) {
[[UIApplication sharedApplication] registerUserNotificationSettings:[UIUserNotificationSettings settingsForTypes:(UIUserNotificationTypeBadge|UIUserNotificationTypeSound|UIUserNotificationTypeAlert) categories:nil]];
}else{
[[UIApplication sharedApplication] registerForRemoteNotificationTypes: (UIUserNotificationTypeBadge|UIUserNotificationTypeSound|UIUserNotificationTypeAlert)];
}
#else
[[UIApplication sharedApplication] registerUserNotificationSettings: (UIUserNotificationTypeBadge|UIUserNotificationTypeSound|UIUserNotificationTypeAlert)];
#endif
由于 Swift 没有预处理器,他们必须发明一种在语言本身内进行此类检查的方法。
如果您想在运行时检查方法的可用性,请注意适当的方法是使用方法 respondsToSelector: 或 instancesRespondToSelector:(后者位于等级)。
您通常希望将两种方法结合起来,即编译时条件编译和运行时检查。
Objective C 方法存在验证,例如在班级层面:
if ([UIImagePickerController instancesRespondToSelector:
@selector (availableCaptureModesForCameraDevice:)]) {
// Method is available for use.
// Your code can check if video capture is available and,
// if it is, offer that option.
} else {
// Method is not available.
// Alternate code to use only still image capture.
}
如果要在运行时测试一个C函数是否存在,那就更简单了:如果存在,则函数本身不为null。
您不能在两种语言中使用相同的方法。