Array 的几种遍历方式

1.  for循环


Student *stu = [Student student];
NSArray *array = [NSArray arrayWithObjects:stu, @"1",@"2",nil];
int count = array.count;//减少调用次数
for( int i=0; i<count; i++){
    NSLog(@"%i-%@", i, [array objectAtIndex:i]);
}


2.  增强for


for(id obj in array){
    NSLog(@"%@",obj);
}

3.  迭代器

<pre name="code" class="objc">    //创建不可改变的词典
    
    NSDictionary *dictionary = [NSDictionary dictionaryWithObjectsAndKeys:@"good lucky",@"why",@"bye bye",@"how",nil];
   
    //输出词典的数量
    NSLog(@"词典的数量= %lu",[dictionary count]);
    
    /*得到词典中所有的键值的过程  NSEnumerator 用来遍历集合中每一处索引的对象*/
    
    //先得到里面所有的键值   objectEnumerator得到里面的对象  keyEnumerator得到里面的键值
    NSEnumerator * enumerator = [dictionary keyEnumerator];//把keyEnumerator替换为objectEnumerator即可得到value值(1)
    
    //定义一个不确定类型的对象
    id object=nil;
    //遍历输出
    while(object = [enumerator nextObject])
    {
        NSLog(@"键值为:%@",object);
        //在这里我们得到的是键值,可以通过(1)得到,也可以通过这里得到的键值来得到它对应的value值
        //通过NSDictionary对象的objectForKey方法来得到
        //其实这里定义objectValue这个对象可以直接用NSObject,因为我们已经知道它的类型了,id在不知道类型的情况下使用
        id objectValue = [dictionary objectForKey:object];
        if(objectValue != nil)
        {
            NSLog(@"%@所对应的value是 %@",object,objectValue);
        }
        
    }
 4.  Block块遍历 
[array enumeratorObjectsUsingBlock:
^(id obj, NSUInteger index, BOOL  *stop){
    NSLog(@"%i-%@",index,obj);
    //若终断循环
    *stop = YES;
}];

5.  do-while

int i = 0;
do {
    NSLog(@"%@",[arr objectAtIndex:i]);
    i++;
} while (i<[arr count]);

6. while-do

int j = 0;
while (j<[arr count]) {
    NSLog(@"%@",[arr objectAtIndex:j]);
    j++;
}

7.

dispatch_apply([arr count], dispatch_get_main_queue(), ^(size_t index){//串行,容易引起主线程堵塞,可以另外开辟线程
    NSLog(@"%ld,%@",index,[arr objectAtIndex:index]);
});

8.

dispatch_apply([arr count], dispatch_get_global_queue(0, 0), ^(size_t index){//并行
    NSLog(@"%ld,%@",index,[arr objectAtIndex:index]);
});

9.

[arr enumerateObjectsUsingBlock: ^(id obj, NSUInteger idx, BOOL *stop){
    NSLog(@"%ld,%@",idx,[arr objectAtIndex:idx]);
}];


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值