我想检查设备的iOS版本是否大于3.1.3 我尝试了以下方法:

[[UIDevice currentDevice].systemVersion floatValue]

但是不管用,我只想要一个:

if (version > 3.1.3) { }

我怎样才能做到这一点呢?


当前回答

根据苹果官方文档的建议:你可以使用nsobjcrtime .h头文件中的NSFoundationVersionNumber。

if (floor(NSFoundationVersionNumber) > NSFoundationVersionNumber_iOS_6_1) {
    // here you go with iOS 7
}

其他回答

Try:

NSComparisonResult order = [[UIDevice currentDevice].systemVersion compare: @"3.1.3" options: NSNumericSearch];
if (order == NSOrderedSame || order == NSOrderedDescending) {
    // OS version >= 3.1.3
} else {
    // OS version < 3.1.3
}

使用nv-ios-version项目(Apache License, Version 2.0)中包含的Version类,很容易获取和比较iOS版本。下面的示例代码转储iOS版本,并检查版本是否大于或等于6.0。

// Get the system version of iOS at runtime.
NSString *versionString = [[UIDevice currentDevice] systemVersion];

// Convert the version string to a Version instance.
Version *version = [Version versionWithString:versionString];

// Dump the major, minor and micro version numbers.
NSLog(@"version = [%d, %d, %d]",
    version.major, version.minor, version.micro);

// Check whether the version is greater than or equal to 6.0.
if ([version isGreaterThanOrEqualToMajor:6 minor:0])
{
    // The iOS version is greater than or equal to 6.0.
}

// Another way to check whether iOS version is
// greater than or equal to 6.0.
if (6 <= version.major)
{
    // The iOS version is greater than or equal to 6.0.
}

项目页面:nv-ios-version TakahikoKawasaki / nv-ios-version

博客:获取并比较iOS版本在运行时与版本类 获取并比较iOS版本在运行时与版本类

试试下面的代码:

NSString *versionString = [[UIDevice currentDevice] systemVersion];

作为yasimturks解决方案的一种变体,我定义了一个函数和一些枚举值,而不是五个宏。我觉得它更优雅,但那是个人品味的问题。

用法:

if (systemVersion(LessThan, @"5.0")) ...

. h文件:

typedef enum {
  LessThan,
  LessOrEqual,
  Equal,
  GreaterOrEqual,
  GreaterThan,
  NotEqual
} Comparison;

BOOL systemVersion(Comparison test, NSString* version);

m文件:

BOOL systemVersion(Comparison test, NSString* version) {
  NSComparisonResult result = [[[UIDevice currentDevice] systemVersion] compare: version options: NSNumericSearch];
  switch (test) {
    case LessThan:       return result == NSOrderedAscending;
    case LessOrEqual:    return result != NSOrderedDescending;
    case Equal:          return result == NSOrderedSame;
    case GreaterOrEqual: return result != NSOrderedAscending;
    case GreaterThan:    return result == NSOrderedDescending;
    case NotEqual:       return result != NSOrderedSame;
  }
}

你应该在名称中添加应用程序的前缀,尤其是比较类型。

我知道这是一个老问题,但是应该有人在available .h中提到编译时宏。这里的所有其他方法都是运行时解决方案,不能在头文件、类类别或ivar定义中工作。

对于这些情况,使用

#if __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_14_0 && defined(__IPHONE_14_0)
  // iOS 14+ code here
#else
  // Pre iOS 14 code here
#endif

不要这样回答