比较Objective-C中的版本号

我正在编写一个接收带有项目和版本号的数据的应用程序。数字的格式类似于“ 1.0.1”或“ 1.2.5”。如何比较这些版本号?我认为必须先将它们格式化为字符串,不是吗?我必须确定“ 1.0.1”之后是“ 1.2.5”吗?



手掌心
浏览 1172回答 3
3回答

慕侠2389804

这是比较版本的最简单方法,请记住“ 1” <“ 1.0” <“ 1.0.0”:NSString* requiredVersion = @"1.2.0";NSString* actualVersion = @"1.1.5";if ([requiredVersion compare:actualVersion options:NSNumericSearch] == NSOrderedDescending) {&nbsp; // actualVersion is lower than the requiredVersion}

湖上湖

我将添加我的方法,该方法将严格的数字版本(无a,b,RC等)与任意数量的组件进行比较。+ (NSComparisonResult)compareVersion:(NSString*)versionOne toVersion:(NSString*)versionTwo {&nbsp; &nbsp; NSArray* versionOneComp = [versionOne componentsSeparatedByString:@"."];&nbsp; &nbsp; NSArray* versionTwoComp = [versionTwo componentsSeparatedByString:@"."];&nbsp; &nbsp; NSInteger pos = 0;&nbsp; &nbsp; while ([versionOneComp count] > pos || [versionTwoComp count] > pos) {&nbsp; &nbsp; &nbsp; &nbsp; NSInteger v1 = [versionOneComp count] > pos ? [[versionOneComp objectAtIndex:pos] integerValue] : 0;&nbsp; &nbsp; &nbsp; &nbsp; NSInteger v2 = [versionTwoComp count] > pos ? [[versionTwoComp objectAtIndex:pos] integerValue] : 0;&nbsp; &nbsp; &nbsp; &nbsp; if (v1 < v2) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return NSOrderedAscending;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; else if (v1 > v2) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return NSOrderedDescending;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; pos++;&nbsp; &nbsp; }&nbsp; &nbsp; return NSOrderedSame;}

拉风的咖菲猫

这是对Nathan de Vries答案的扩展,以解决1 <1.0 <1.0.0等问题。首先,我们可以使用以下NSString类别解决版本字符串中多余的“ .0”的问题:@implementation NSString (VersionNumbers)- (NSString *)shortenedVersionNumberString {&nbsp; &nbsp; static NSString *const unnecessaryVersionSuffix = @".0";&nbsp; &nbsp; NSString *shortenedVersionNumber = self;&nbsp; &nbsp; while ([shortenedVersionNumber hasSuffix:unnecessaryVersionSuffix]) {&nbsp; &nbsp; &nbsp; &nbsp; shortenedVersionNumber = [shortenedVersionNumber substringToIndex:shortenedVersionNumber.length - unnecessaryVersionSuffix.length];&nbsp; &nbsp; }&nbsp; &nbsp; return shortenedVersionNumber;}@end通过上述NSString类别,我们可以缩短版本号,以删除不必要的.0NSString* requiredVersion = @"1.2.0";NSString* actualVersion = @"1.1.5";requiredVersion = [requiredVersion shortenedVersionNumberString]; // now 1.2actualVersion = [actualVersion shortenedVersionNumberString]; // still 1.1.5现在,我们仍然可以使用Nathan de Vries提出的简单漂亮的方法:if ([requiredVersion compare:actualVersion options:NSNumericSearch] == NSOrderedDescending) {&nbsp; // actualVersion is lower than the requiredVersion}
打开App,查看更多内容
随时随地看视频慕课网APP