问题
I need to get the user's app version number and compare it with the current app version on my server. If the user's app version is lower, then he will get a pop-up to update his app. While doing this, I need to compare the version of the app with the versions that are available. How can I compare the strings which are in the format "2.0.1"
and "2.0.09"
and get the highest one, in Objective-C?
回答1:
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
}
回答2:
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.
回答3:
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"];
来源:https://stackoverflow.com/questions/7004655/comparing-strings-with-the-format-2-0-1-2-0-09