0

OK、ループを終了するためにある種の終了コマンドを使用することを真剣に検討しているわけではありませんが、この状況では、1 つを使用できると確信している場合は 2 つの方法を使用する傾向があります。

この例では、最善のアプローチは何ですか?

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 に答える