iOS - 比较应用版本

时间:2014-12-16 12:01:14

标签: ios objective-c version string-comparison info.plist

我想在App Store上更新我的应用。在更新后首次打开应用程序时,我希望它能够同步一些内容。因此,我需要一种方法来查看它是否是更新后的第一次启动。

我想到的解决方案是:将应用版本存储在NSUserDefaults中,如下所示:

NSString *oldVersion = [[NSUserDefaults standardUserDefaults] objectForKey:@"appVersion"];
NSString *currentVersion = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"];
[[NSUserDefaults standardUserDefaults] setObject:currentVersion forKey:@"appVersion"];
[[NSUserDefaults standardUserDefaults] synchronize];

现在我有oldVersioncurrentVersion,我需要做的就是比较它们。我想知道oldVersion是否小于currentVersion。但它们是弦乐。我该如何检查oldVersion < currentVersion

我知道我可以检查他们是否不平等。但我希望为将来的更新做好准备。因为对于版本3,我希望为此2执行的同步可能会有所不同等等。

3 个答案:

答案 0 :(得分:10)

您可以使用自然排序顺序(将在1.1之后考虑1.10,与字典排序顺序不同)比较数字版本号,如下所示:

BOOL isNewer = ([currentVersion compare:oldVersion options:NSNumericSearch] == NSOrderedDescending)

答案 1 :(得分:0)

Swift 3.0中的代码作为字符串扩展,适用于包含额外零的版本。(例如:1.0.0&amp; 1.0

```

/// Inner comparison utility to handle same versions with different length. (Ex: 1.0.0 & 1.0)
private func compare(toVersion targetVersion: String) -> ComparisonResult {

    let versionDelimiter = "."
    var result: ComparisonResult = .orderedSame
    var versionComponents = components(separatedBy: versionDelimiter)
    var targetComponents = targetVersion.components(separatedBy: versionDelimiter)
    let spareCount = versionComponents.count - targetComponents.count

    if spareCount == 0 {
        result = compare(targetVersion, options: .numeric)
    } else {
        let spareZeros = repeatElement("0", count: abs(spareCount))
        if spareCount > 0 {
            targetComponents.append(contentsOf: spareZeros)
        } else {
            versionComponents.append(contentsOf: spareZeros)
        }
        result = versionComponents.joined(separator: versionDelimiter)
            .compare(targetComponents.joined(separator: versionDelimiter), options: .numeric)
    }
    return result
}

public func isVersion(equalTo targetVersion: String) -> Bool { return compare(toVersion: targetVersion) == .orderedSame }
public func isVersion(greaterThan targetVersion: String) -> Bool { return compare(toVersion: targetVersion) == .orderedDescending }
public func isVersion(greaterThanOrEqualTo targetVersion: String) -> Bool { return compare(toVersion: targetVersion) != .orderedAscending }
public func isVersion(lessThan targetVersion: String) -> Bool { return compare(toVersion: targetVersion) == .orderedAscending }
public func isVersion(lessThanOrEqualTo targetVersion: String) -> Bool { return compare(toVersion: targetVersion) != .orderedDescending }

```

答案 2 :(得分:0)

雨燕4

if cuurentVersionString.compare(forceUpdate, options: .numeric) == .orderedAscending {
            print("force")
            state = .force
        }

这意味着强制更新版本高于当前版本