Objective-C 学习笔记 - part 8 - 快速枚举

快速枚举使用的语法:
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"


posted on 2011-08-17 15:27  沙加  阅读(1730)  评论(0编辑  收藏  举报

导航