三种方式枚举数组:快速枚举、使用块枚举或使用NSEnumerator
对象。
顾名思义,快速枚举通常比使用其他技巧访问数组中的对象要快。快速枚举是一项需要特定语法的语言功能:
快速枚举是一项需要特定语法的语言功能:for (
type variable in
array)
NSArray *myArray = // get array |
for (NSString *cityName in myArray) { |
if ([cityName isEqualToString:@"Cupertino"]) { |
NSLog(@"We're near the mothership!"); |
break; |
} |
} |
数个 NSArray
方法使用块来枚举数组,其中最简单的是 enumerateObjectsUsingBlock:
。此块具有三个参数:当前对象、其索引和引用的 Boolean 值(设置为 YES
时终止枚举)。此块中的代码执行的工作,与快速枚举语句中大括号内的代码完全相同。
NSArray *myArray = // get array |
[myArray enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) { |
if ([obj isEqual:@"Cupertino"]) { |
NSLog(@"We're near the mothership!"); |
*stop = YES; |
} |
}]; |