Comparing strings with the format "2.0.1", "2.0.09"

I need to get the version number of the application for the user and compare it with the current version of the application on my server. If the version of the user application is lower, he will receive a pop-up window to update his application. In doing this, I need to compare the version of the application with the versions that are available. How to compare strings that are in the format "2.0.1" and "2.0.09" and get the highest number in Objective-C?

+5
source share
3 answers

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 } 
+5
source

If your lines are in the form of "2.0.1", etc., you can simply compare them with the appropriate parameters:

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

The above will return “ YES ” if localVersion is not older than currentVersion on the server, and “ NO ” otherwise (if I have it right).

This is a common thing when you check the local version of iOS installed on iDevice.

+4
source

As answered in this post; Compare Version Numbers in Objective-C

Check out my NSString category, which implements simple version checking on github; https://github.com/stijnster/NSString-compareToVersion

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

This will return an 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"]; 
+3
source

Source: https://habr.com/ru/post/953066/


All Articles