0

好的,我并不认真地希望使用某种退出命令来退出循环,但在这种情况下,我倾向于使用两种方法,当我确定我可以使用一种时。

对于这个例子,最好的方法是什么?

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;
}
4

2 回答 2

1
NSComparisonResult result = NSOrderedSame;
for(int i = 0; i < [leftFields count]; i++) {
    result = [[leftFields objectAtIndex:i] compare:[rightFields objectAtIndex:i] options:NSNumericSearch];
    if (result != NSOrderedSame) {
        break;
    }
}
return result;

这是你要找的吗?

于 2012-09-06T21:15:37.653 回答
0

如果我正确理解您的问题,您可以只使用while循环而不是for循环,例如:

i = 0;
NSComparisonResult result;
while (i < [lefFields count]  &&  
       NSOrderedSame == (result = [[leftFields objectAtIndex:i] compare:[rightFields objectAtIndex:i] options:NSNumericSearch]))
    ++i;
return result;
于 2012-09-06T20:37:51.553 回答