如何在不使用 Objective-C 命令的情况下结合两种方法,"exit"其中我有一个循环?



好吧,我并不是真的想使用某种退出命令来退出循环,但在这种情况下,我倾向于使用两种方法,而我确信我可以使用其中一种。

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

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

这就是你要找的吗?

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

i = 0;
NSComparisonResult result;
while (i < [lefFields count]  &&  
       NSOrderedSame == (result = [[leftFields objectAtIndex:i] compare:[rightFields objectAtIndex:i] options:NSNumericSearch]))
    ++i;
return result;

相关内容

  • 没有找到相关文章

最新更新