I’ve found the following code at http://snipplr.com/view/2771
Which is pretty good, almost exactly what I was looking for, but if I use the values @"1.4.5", @"10.4" it produces the wrong result, saying that the first number is lower.
Arghhhh Late night coding, sorry I read 10.4 as 1.4 🙁
I’m unsure why compare is having an issue and what the problem is ?
/*
* compareVersions(@"10.4", @"10.3"); //
returns NSOrderedDescending (1) - aka first number is higher
* compareVersions(@"10.5", @"10.5.0"); //
returns NSOrderedSame (0)
* compareVersions(@"10.4 Build 8L127", @"10.4 Build 8P135"); //
returns NSOrderedAscending (-1) - aka first number is lower
*/
NSComparisonResult compareVersions(NSString* leftVersion, NSString* rightVersion)
{
int i;
// Break version into fields (separated by '.')
NSMutableArray *leftFields = [[NSMutableArray alloc] initWithArray:[leftVersion componentsSeparatedByString:@"."]];
NSMutableArray *rightFields = [[NSMutableArray alloc] initWithArray:[rightVersion componentsSeparatedByString:@"."]];
// Implict ".0" in case version doesn't have the same number of '.'
if ([leftFields count] < [rightFields count]) {
while ([leftFields count] != [rightFields count]) {
[leftFields addObject:@"0"];
}
} else if ([leftFields count] > [rightFields count]) {
while ([leftFields count] != [rightFields count]) {
[rightFields addObject:@"0"];
}
}
.
// Do a numeric comparison on each field
for(i = 0; i < [leftFields count]; i++) {
NSComparisonResult result = [[leftFields objectAtIndex:i] compare:[rightFields objectAtIndex:i] options:NSNumericSearch];
if (result != NSOrderedSame) {
[leftFields release];
[rightFields release];
return result;
}
}
[leftFields release];
[rightFields release];
return NSOrderedSame;
}
[I posted this earlier today, but it was not selected as the answer, and it may be more appropriate to your problem. There are other techniques, you can look here and here for other solutions.]
What I do is take that string and break it into components:
What this does is give you a normalized value you can use for comparison, and will generally compare releases that have different “depths”, ie 1.5 and 1.5.2.
It breaks if you have more than 100 point releases (ie any number is > 100) and also will declare 1.5.0 == 1.5. That said, its short, sweet, and simple to use.
EDIT: if you use the NSString ‘compare:options:’ method, make sure you have your string well groomed: