How to use compare on a version number where theres less parts in one number in Objective-C?

前端 未结 9 601
感情败类
感情败类 2021-01-22 02:30

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\", @

9条回答
  •  闹比i
    闹比i (楼主)
    2021-01-22 02:56

    [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:

    NSArray *array = [myVersion componentsSeparatedByCharactersInSet:@"."];
    
    NSInteger value = 0;
    NSInteger multiplier = 1000000;
    for(NSString *n in array) {
      value += [n integerValue] * multiplier;
      multiplier /= 100;
    }
    

    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:

        s1 = @"1.";
        s2 = @"1";
        NSLog(@"Compare %@ to %@ result %d", s1, s2, (int)[s1 compare:s2 options:NSNumericSearch]);
        s1 = @"20.20.0";
        s2 = @"20.20";
        NSLog(@"Compare %@ to %@ result %d", s1, s2, (int)[s1 compare:s2 options:NSNumericSearch]);
    
    2012-09-06 11:26:24.793 xxx[59804:f803] Compare 1. to 1 result 1
    2012-09-06 11:26:24.794 xxx[59804:f803] Compare 20.20.0 to 20.20 result 1
    

提交回复
热议问题