快速枚举使用的语法: for ( Type newVariable in expression ) { statements } or Type existingItem; for ( existingItem in expression ) { statements }
枚举期间对象不能被改变。
使用快速枚举的三个类: NSArray, NSDictionary, NSSet
如何使用:
NSArray *array = [NSArray arrayWithObjects: @"One", @"Two", @"Three", @"Four", nil]; for (NSString *element in array) { NSLog(@"element: %@", element); } NSDictionary *dictionary = [NSDictionary dictionaryWithObjectsAndKeys: @"quattuor", @"four", @"quinque", @"five", @"sex", @"six", nil]; NSString *key; for (key in dictionary) { NSLog(@"English: %@, Latin: %@", key, [dictionary objectForKey:key]); }
也可以使用 enumeration : NSArray *array = [NSArray arrayWithObjects: @"One", @"Two", @"Three", @"Four", nil]; NSEnumerator *enumerator = [array reverseObjectEnumerator]; for (NSString *element in enumerator) { if ([element isEqualToString:@"Three"]) { break; } } NSString *next = [enumerator nextObject]; // next = "Two"
|
请发表评论