Comparing strings with the format “2.0.1”, “2.0.09”

◇◆丶佛笑我妖孽 提交于 2019-12-05 07:34:42
csano

How about using the compare:options: method of the NSString class?

NSString *v1 = @"2.0.1";
NSString *v2 = @"2.1";

NSComparisonResult result = [v1 compare:v2 options:NSNumericSearch];
if (result == NSOrderedSame || result == NSOrderedDescending) {
    // do
} else {
    // do
}

If your strings are all of the form "2.0.1" etc. you can just compare them as is with the right options:

([localVersionString compare:currentVersionString
                     options:NSNumericSearch] != NSOrderedAscending);

The above would return "YES" if the localVersion is no older than the currentVersion on the server, and "NO" otherwise (assuming I have this the right way round).

This is the usual thing to do when checking the local version of iOS installed on an iDevice.

Stijnster

As answered in this post; Compare version numbers in Objective-C

Check out my NSString category that implements easy version checking on github; https://github.com/stijnster/NSString-compareToVersion

[@"1.2.2.4" compareToVersion:@"1.2.2.5"];

This will return a NSComparisonResult which is more accurate than using;

[@"1.2.2" compare:@"1.2.2.5" options:NSNumericSearch]

Helpers are also added;

[@"1.2.2.4" isOlderThanVersion:@"1.2.2.5"];
[@"1.2.2.4" isNewerThanVersion:@"1.2.2.5"];
[@"1.2.2.4" isEqualToVersion:@"1.2.2.5"];
[@"1.2.2.4" isEqualOrOlderThanVersion:@"1.2.2.5"];
[@"1.2.2.4" isEqualOrNewerThanVersion:@"1.2.2.5"];
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!