实现了NSFastEnumeration协议的集合的都可以使用快速枚举的特性,如NSArray, NSDictionary, NSSet, NSEnumerator等。注意这里NSEnumerator也实现了NSFastEnumeration协议,这样可以执行一些特殊的任务,如使用reverseObjectEnumerator来对数组进行反同查询。
快速枚举的格式如下:
for(type loopVariable in expression) { 语句 }
下面的例子关注一下不同退出循环的方式,loopVariable值的变化:
#import <Foundation/Foundation.h> #import "Photo.h" int main (int argc, const char * argv[]) { NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init]; NSArray *array = [NSArray arrayWithObjects:[[Photo alloc] init],[[Photo alloc] init],[[Photo alloc] init], nil]; Photo *photo; for(photo in array) { [photo draw]; } NSLog(@"经过完整遍历后,循环变量photo的值为 = %@",photo); int n=0; for(photo in array) { if(n == 2)break; [photo draw]; n++; } NSLog(@"通过break退出循环,循环变量photo的值为 = %@,是最后一个遍历的值。",photo); [pool drain]; return 0; }
运行结果:
[Switching to process 4357 thread 0x0] 2011-05-11 10:27:04.235 demo06[4357:903] 55 2011-05-11 10:27:04.249 demo06[4357:903] 18 2011-05-11 10:27:04.252 demo06[4357:903] 51 2011-05-11 10:27:04.257 demo06[4357:903] 经过完整遍历后,循环变量photo的值为 = (null) 2011-05-11 10:27:04.262 demo06[4357:903] 60 2011-05-11 10:27:04.263 demo06[4357:903] 33 2011-05-11 10:27:04.264 demo06[4357:903] 通过break退出循环,循环变量photo的值为 = <Photo: 0x10010ca70>,是最后一个遍历的值。
NSDictionary
#import <Foundation/Foundation.h> #import "Photo.h" int main (int argc, const char * argv[]) { NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init]; NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys: [[Photo alloc] init], @"p1", [[Photo alloc] init], @"p2", [[Photo alloc] init], @"p3", nil]; //for...in 只能遍历NSDictionary的Key NSString *key; for(key in dict) { [[dict objectForKey:key] draw]; } //如果要遍历对象,需要通过objectEnumerator进行转换 for(id obj in [dict objectEnumerator]) { [obj draw]; } [pool drain]; return 0; }