for for for condition for multiple multiple condition in single if statement

时间:2015-01-12 05:05:13

标签: objective-c for-loop

我见过像这样的代码

if ([[dict objectForKey:@"name"] rangeOfString:@“AB”].location != NSNotFound ||
    [[dict objectForKey:@"name"] rangeOfString:@“CD”].location != NSNotFound ||
    [[dict objectForKey:@"name"] rangeOfString:@“EF”].location != NSNotFound ||
    [[dict objectForKey:@"name"] rangeOfString:@“GH”].location != NSNotFound ||
    [[dict objectForKey:@"name"] rangeOfString:@“IJ”].location != NSNotFound ||){
    // do something
   }

我改为:

NSArray *myArray = [NSArray arrayWithObjects:@“AB”,
                @"CD", @"EF", @"GH", @"IJ", nil];

for (id object in myArray) {
    if ([[dict objectForKey:@"name”] rangeOfString: id].location != NSNotFound){
        // do something
        break;
    }
}

我知道更改代码后可读性更好。它还有其他优点吗?

1 个答案:

答案 0 :(得分:2)

我认为没有任何实质性差异。通过将字典访问拉出循环,您可以进一步提高可读性和简洁性。

// probably done for you by the compiler, but still prettier to look at...
NSString *name = dict[@"name"];

for (id object in myArray) {
    if ([name rangeOfString:id].location != NSNotFound){
        // do something
        break;
    }
}