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?
Asked
Active
Viewed 3,200 times
6
3 Answers
6
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
}
4
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.

Ken
- 30,811
- 34
- 116
- 155
-
NSNumericSearch is a much better option than doing it manually. – benzado Aug 10 '11 at 01:25
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"];
-
thanks Stijnster, your category is great……but going to really need a Swift version soon… – wuf810 Jul 14 '16 at 15:23