iOS 版本号比较大小

2020-06-30突然想到一个比较骚的比较办法,去掉版本号中间的 "." 然后比大小。

字符串前拼接 "0.",是为了方便后续拓展版本(例如:1.0升级到1.0.1)

- (BOOL)versionCompareFirst:(NSString *)first andVersionSecond:(NSString *)second
{
    first = [first stringByReplacingOccurrencesOfString:@"." withString:@""];
    first = [@"0." stringByAppendingString:first];

    second = [second stringByReplacingOccurrencesOfString:@"." withString:@""];
    second = [@"0."stringByAppendingString:second];
    return [first floatValue] >= [second floatValue];
}

===========================2020-10-13 更新(果然凭空想象的都不靠谱)
遗忘了1.9到1.10的这类情况,还是老老实实遍历吧

- (BOOL)versionCompareFirst:(NSString *)first andVersionSecond:(NSString *)second
{
    NSArray *firstArray = [first componentsSeparatedByString:@"."];
    NSArray *secondArray = [second componentsSeparatedByString:@"."];
    for (int i = 0; i < firstArray.count && i < secondArray.count; i++) {
        NSInteger a = [[firstArray objectAtIndex:i] integerValue];
        NSInteger b = [[secondArray objectAtIndex:i] integerValue];
        if (a > b) {
            return YES;
        }
    }
    return NO;
}

你可能感兴趣的:(iOS 版本号比较大小)