Posted By

0xced on 06/01/07


Tagged

textmate String version compare dot


Versions (?)

Who likes this?

1 person have marked this snippet as a favorite

tcol


Compare two version strings


 / Published in: Objective C
 

  1. /*
  2.  * compareVersions(@"10.4", @"10.3") returns NSOrderedDescending (1)
  3.  * compareVersions(@"10.5", @"10.5.0") returns NSOrderedSame (0)
  4.  * compareVersions(@"10.4 Build 8L127", @"10.4 Build 8P135") returns NSOrderedAscending (-1)
  5.  */
  6. NSComparisonResult compareVersions(NSString* leftVersion, NSString* rightVersion)
  7. {
  8. int i;
  9.  
  10. // Break version into fields (separated by '.')
  11. NSMutableArray *leftFields = [[NSMutableArray alloc] initWithArray:[leftVersion componentsSeparatedByString:@"."]];
  12. NSMutableArray *rightFields = [[NSMutableArray alloc] initWithArray:[rightVersion componentsSeparatedByString:@"."]];
  13.  
  14. // Implict ".0" in case version doesn't have the same number of '.'
  15. if ([leftFields count] < [rightFields count]) {
  16. while ([leftFields count] != [rightFields count]) {
  17. [leftFields addObject:@"0"];
  18. }
  19. } else if ([leftFields count] > [rightFields count]) {
  20. while ([leftFields count] != [rightFields count]) {
  21. [rightFields addObject:@"0"];
  22. }
  23. }
  24.  
  25. // Do a numeric comparison on each field
  26. for(i = 0; i < [leftFields count]; i++) {
  27. NSComparisonResult result = [[leftFields objectAtIndex:i] compare:[rightFields objectAtIndex:i] options:NSNumericSearch];
  28. if (result != NSOrderedSame) {
  29. [leftFields release];
  30. [rightFields release];
  31. return result;
  32. }
  33. }
  34.  
  35. [leftFields release];
  36. [rightFields release];
  37. return NSOrderedSame;
  38. }

Report this snippet  

You need to login to post a comment.