1.快速遍历数组的每一个元素:
NSArray * array = [NSArray arrayWithObjects:@"zhangsan",@"lisi",@"wangwu",@"zhaoda",@"qianer",nil];
//方法一:快速枚举(for...in):效率最高,代码的可读性强,代码简洁易懂
for(NSString obj in array)
{
NSLog(@"%@",obj);
}
//方法二:for循环遍历
for(int i = 0; i < [array count]; i++)
{
NSString * obj = [array objectAtIndex:i];
NSLog(@"%@",obj);
}
//方法三:使用枚举器NSEnumerator
NSEnumerator * enumerator = [array reverseObjectEnumerator];
NSString * obj = nil;
while(obj = [enumerator nextObject])
{
NSLog(@"%@",obj);
}
//方法四:(block)使用专业的枚举方式
[array enumerateObjectsUsingBlock:^(id obj,NSUInteger idx,BOOL * stop){
NSLog(@"%@---%lu",obj,idx);
if(idx == 1){
*stop = YES;
}
}];
2.快速遍历字典中的每一个元素
NSDictionary * dic = [NSDictionary dictionaryWithObjectsAndKeys:@"jack",@"name",@"19",@"age",@"1.8",@"height",nil];
NSArray * allkeys = [dic allkeys];
for(int i = 0; i < [dic count]; i++)
{
NSString * key = [allkeys objectAtIndex:i];
NSString * obj = [dic objectForKey:key];
NSLog(@"obj=%@,key=%@",obj,key);
}
3.快速遍历集合中的元素(NSSet)
NSSte * set = [NSSet setWithObjects:@"mingren",@"zuozhu",@"haizei",@"xiaoxin",nil];
NSString * obj = [set allObjects];
for(int i = 0; i < [set count]; i++)
{
NSLog(@"%@",[obj objectAtIndex:i]);
}
以上就是有关数组,字典和集合的遍历元素的方法,方法还有很多,希望和各位同学相互学习,相互成长!