快速枚举是Objective-C 2.0 中提供的一种简洁的特色语法,可以安全又快速地对集合中的元素进行枚举。
标准形式如下:
for (Type newVariable in expression) {
statements;
}
//或者
Type variable;
for (variable in expression) {
statements;
}
举个��
// 使用NSArray的快速枚举
NSArray *array = [NSArray arrayWithObjects:@"one", @"two", @"three", @"four", nil];
for (NSArray *element in array) {
NSLog(@"element : %@", element);
}
// 使用NSDictionary的快速枚举
NSDictionary *dic = [[NSDictionary alloc] dictionaryWithObjectsAndKeys:@"one", @"1", @"two", @"2", @"three", @"3", nil];
NSString *key;
for (key in dic) {
NSLog(@"english : %@, number : %@", [dic valueForKey: key], key);
}