好的,我并不认真地希望使用某种退出命令来退出循环,但在这种情况下,我倾向于使用两种方法,当我确定我可以使用一种时。
对于这个例子,最好的方法是什么?
typedef enum {
FirstParamHigherThanSecond,
FirstParamLowerThanSecond,
ParamsEqual
} VersionStatus;
VersionStatus compareVersions(NSString* left, NSString* right) {
VersionStatus retVal;
NSComparisonResult res = analyszeVersions(left, right);
if (res == NSOrderedSame) {
retVal = ParamsEqual;
} else if (res == NSOrderedDescending) {
retVal = FirstParamHigherThanSecond;
} else if ( res == NSOrderedAscending) {
retVal = FirstParamLowerThanSecond;
}
return retVal;
}
.
NSComparisonResult analyszeVersions(NSString* leftVersion, NSString* rightVersion)
{
int i;
NSMutableArray *leftFields = [[NSMutableArray alloc] initWithArray:[leftVersion componentsSeparatedByString:@"."]];
NSMutableArray *rightFields = [[NSMutableArray alloc] initWithArray:[rightVersion componentsSeparatedByString:@"."]];
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"];
}
}
for(i = 0; i < [leftFields count]; i++) {
NSComparisonResult result = [[leftFields objectAtIndex:i] compare:[rightFields objectAtIndex:i] options:NSNumericSearch];
if (result != NSOrderedSame) {
return result;
}
}
return NSOrderedSame;
}