我在 http://snipplr.com/view/2771 找到了以下代码
这非常好,几乎正是我想要的,但是如果我使用值 @"1.4.5", @"10.4"
它会产生错误的结果,说第一个数字较低。
Arghhhh 深夜编码,抱歉,我将 10.4 读作 1.4
我不确定为什么 compare 有问题,问题是什么?
/*
* 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;
}
[我今天早些时候发布了这个,但它没有被选为答案,它可能更适合你的问题。还有其他技巧,可以看here和 here其他解决方案。]
我所做的就是将该字符串分解为组件:
NSArray *array = [myVersion componentsSeparatedByCharactersInSet"."];
NSInteger value = 0;
NSInteger multiplier = 1000000;
for(NSString *n in array) {
value += [n integerValue] * multiplier;
multiplier /= 100;
}
它的作用是为您提供一个可用于比较的标准化值,并且通常会比较具有不同“深度”的版本,即 1.5 和 1.5.2。
如果您有超过 100 个点发布(即任何数字大于 100),它就会中断,并且还会声明 1.5.0 == 1.5。也就是说,它简短、甜美且易于使用。
编辑:如果您使用 NSString 'compareptions:' 方法,请确保您的字符串修饰得很好:
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
关于iphone - 如何在Objective-C中一个数字中的部分较少的版本号上使用比较?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12308659/
欢迎光临 OGeek|极客世界-中国程序员成长平台 (https://ogeek.cn/) | Powered by Discuz! X3.4 |