Comparing version numbers

后端 未结 8 1599
予麋鹿
予麋鹿 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:18

    I like Mike's (less code) answer but this should also work even if there is a question about the compare option NSNumericSearch works.

    - (NSComparisonResult)compareVersion:(NSString *)versionA to:(NSString *)versionB
    {
       NSArray *versionAComp = [versionA componentsSeparatedByString:@"."];
       NSArray *versionBComp = [versionB componentsSeparatedByString:@"."];
    
       __block NSComparisonResult result = NSOrderedSame;
    
       [versionAComp enumerateObjectsUsingBlock:
       ^(NSString *obj, NSUInteger idx, BOOL *stop)
       {
            // handle abbreviated versions.
            if (idx > versionBComp.count -1)
            {
                *stop = YES;
                return;
            }
    
            NSInteger verAInt = [versionAComp[idx] integerValue];
            NSInteger verBInt = [versionBComp[idx] integerValue];
    
            if (verAInt != verBInt)
            {
                if (verAInt < verBInt)
                    result = NSOrderedAscending;
                else
                    result = NSOrderedDescending;
    
                *stop = YES;
                return;
            }
        }];
       return result; 
    }
    

提交回复
热议问题