Comparing version numbers

后端 未结 8 1586
予麋鹿
予麋鹿 2020-12-11 11:39

Some time ago, I read that comparing version numbers can be done using the following code snippet:

NSString *vesrion_1 = @\"1.2.1\";
NSString *version_2 = @\         


        
8条回答
  •  独厮守ぢ
    2020-12-11 12:27

    NSNumericSearch should do exactly what you want. It handles all the cases you would expect from a version number. For a previous project I wrote a bunch of test cases for this:

    + (NSComparisonResult)compareBundleVersion:(NSString *)a withBundleVersion:(NSString *)b
    {
        return [a compare:b options:NSNumericSearch];
    }
    
    STAssertEquals(NSOrderedSame, [self compareBundleVersion:@"1" withBundleVersion:@"1"], nil);
    STAssertEquals(NSOrderedSame, [self compareBundleVersion:@"1.0" withBundleVersion:@"1.0"], nil);
    STAssertEquals(NSOrderedSame, [self compareBundleVersion:@"1.1.12" withBundleVersion:@"1.1.12"], nil);
    
    STAssertEquals(NSOrderedAscending, [self compareBundleVersion:@"1" withBundleVersion:@"2"], nil);
    STAssertEquals(NSOrderedAscending, [self compareBundleVersion:@"1" withBundleVersion:@"1.1"], nil);
    STAssertEquals(NSOrderedAscending, [self compareBundleVersion:@"1.0" withBundleVersion:@"1.1"], nil);
    STAssertEquals(NSOrderedAscending, [self compareBundleVersion:@"1.1.12" withBundleVersion:@"1.1.13"], nil);
    STAssertEquals(NSOrderedAscending, [self compareBundleVersion:@"1.1.12" withBundleVersion:@"1.2.1"], nil);
    
    STAssertEquals(NSOrderedDescending, [self compareBundleVersion:@"1.1" withBundleVersion:@"1"], nil);
    STAssertEquals(NSOrderedDescending, [self compareBundleVersion:@"1.1" withBundleVersion:@"1.0"], nil);
    STAssertEquals(NSOrderedDescending, [self compareBundleVersion:@"1.1.13" withBundleVersion:@"1.1.12"], nil);
    STAssertEquals(NSOrderedDescending, [self compareBundleVersion:@"1.2.1" withBundleVersion:@"1.1.12"], nil);
    

    I have also tested this with the previous cases mentioned by another poster:

    STAssertEquals(NSOrderedDescending, [self compareBundleVersion:@"1.30" withBundleVersion:@"1.3"], nil);
    STAssertEquals(NSOrderedDescending, [self compareBundleVersion:@"1.19" withBundleVersion:@"1.3"], nil);
    

    Everything passes as you would expect.

提交回复
热议问题