快速枚举,不仅可以遍历字典,数组(NSArray)、集合(NSSet)也可以。以下例子是字典
1.先创建一个字典
NSDictionary *dic = [[NSDictionary alloc]initWithObjectsAndKeys:
@"piao1",@"mingzu1",
@"jianai",@"book2",
@"xiaofuren",@"book3",
@"baoma",@"car1",
@"baoshijie",@"car2",
@"lanbojini",@"car3",nil];
2.//快速枚举 快速遍历 用的 for in
for (<#type *object#> in <#collection#>) {
<#statements#>
}
id 是任何型 key是名字任意 dic是创建字典的名字 或叫做遍历的对象要是知道什么类型(比如是数组类型)可以写成for(NSArray *string in array)NSLog(@"快速枚举 快速遍历");
for (id key in dic) {
NSString *object=[dic objectForKey:key];
NSLog(@"%@ = %@",key,object);
}
2015-11-13 20:11:45.203 LessionFive[7841:101319] 快速枚举 快速遍历
2015-11-13 20:11:45.203 LessionFive[7841:101319] book2 = jianai
2015-11-13 20:11:45.203 LessionFive[7841:101319] car1 = baoma
2015-11-13 20:11:45.203 LessionFive[7841:101319] car2 = baoshijie
2015-11-13 20:11:45.204 LessionFive[7841:101319] car3 = lanbojini
2015-11-13 20:11:45.204 LessionFive[7841:101319] mingzu1 = piao1
2015-11-13 20:11:45.204 LessionFive[7841:101319] book3 = xiaofuren
3.////枚举器
NSLog(@"\n枚举器");
id key=[enumerator1 nextObject];//获取字典中的下标,即key值
while (key) {//判断下标key值
id object=[dic objectForKey:key];//获取下标key对应的value值
NSLog(@"%@",object);//输出value值
key=[enumerator1 nextObject];//下一个key
}