虽然在目标 c 中使用 foreach 风格的循环无法直接实现这一点,但有几种方法可以完成相同的任务。
请假设
NSArray *myArrayOfStrings = @[@"Apple", @"Pear", @"Orange", @"Grape"];
标准 For 循环
for (int i = 0; i < [myArrayOfStrings count]; i++) {
NSString *string = [myArrayOfStrings objectAtIndex:i];
NSString *next_string = @"nothing";
if (i + 1 < [myArrayOfStrings count]) { // Prevent exception on the final loop
next_string = [myArrayOfStrings objectAtIndex:i + 1];
}
NSLog(@"%@ comes before %@", string, next_string);
}
对象枚举
[myArrayOfStrings enumerateObjectsUsingBlock:^(NSString *string, NSUInteger idx, BOOL *stop) {
NSString *next_string = @"nothing";
if (idx + 1 < [myArrayOfStrings count]) { // Prevent exception on the final loop
next_string = [myArrayOfStrings objectAtIndex:idx + 1];
}
NSLog(@"%@ comes before %@", string, next_string);
}];
这两个选项都输出:
Apple comes before Pear
Pear comes before Orange
Orange comes before Grape
Grape comes before nothing