NSEnumerator
集合类(如:NSArray、NSSet、NSDictionary等)均可获取到NSEnumerator, 该类是一个抽象类,没有用来创建实例的公有接口。NSEnumerator的nextObject方法可以遍历每个集合元素,结束返回nil,通过与while结合使用可遍历集合中所有项。
例子中使用了与前例相同的Photo对象,具体定义参考 隐式循环 这一节。
#import <Foundation/Foundation.h> #import "Photo.h" int main (int argc, const char * argv[]) { NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init]; //while+NSEnumerator //定义对象的数组 NSArray *array = [NSArray arrayWithObjects:[[Photo alloc] init], [[Photo alloc] init],[[Photo alloc] init], nil]; //通过objectEnumberator获取集合的NSEnumerator NSEnumerator *myEnumerator = [array objectEnumerator]; Photo *photo; //nextObject遍历每一项,结束返回nil //注意这里使用的是“=”号,所以最外面还要再添加一对() while((photo = [myEnumerator nextObject])) { [photo draw]; } [pool drain]; return 0; }
NSSet allObjects
#import <Foundation/Foundation.h> #import "Photo.h" int main (int argc, const char * argv[]) { NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init]; //NSSet allObjects NSSet *set = [NSSet setWithObjects:[[Photo alloc] init], [[Photo alloc] init],[[Photo alloc] init], nil]; //allObjects仅能获取NSArray,需要再次调用objectEnumberator //并且获取的数组顺序不确定。 NSEnumerator *myEnumerator = [[set allObjects] objectEnumerator]; Photo *photo; while((photo = [myEnumerator nextObject])) { [photo draw]; } [pool drain]; return 0; }
NSDictionary allValues allKeys
#import <Foundation/Foundation.h> #import "Photo.h" int main (int argc, const char * argv[]) { NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init]; //NSDictionary allValues //NSDictionary 添加项时是value在前j,key在后的,与C#相反 NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys: [[Photo alloc] init], @"p1", [[Photo alloc] init], @"p2", [[Photo alloc] init], @"p3", nil]; //allValues 只能获取字典中值的数组列表,注意列表是无序的。 NSEnumerator *myEnumerator = [[dict allValues] objectEnumerator]; Photo *photo; while((photo = [myEnumerator nextObject])) { [photo draw]; } //allKeys 遍历字典中的所有key列表,然后能过objectForKey获取值。注意列表是无序的。 myEnumerator = [[dict allKeys] objectEnumerator]; NSString *key; while((key = [myEnumerator nextObject])) { //objectForKey从字典中获取key对应的值 [[dict objectForKey:key] draw]; } [pool drain]; return 0; }