zoukankan      html  css  js  c++  java
  • iOS中遍历数组的几种方法

        通过在网上收集和自己的实际经历,总结了下数组的遍历方法。如果其他朋友有更好的方法,可以与我一同分享。

        //第一种,OC自带方法
        //默认为正序遍历
        [arr enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
            NSLog(@"%ld,%@",idx,[arr objectAtIndex:idx]);
        }];
        //NSEnumerationReverse参数为倒序遍历
        [arr enumerateObjectsWithOptions:NSEnumerationReverse usingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
            NSLog(@"%ld,%@",idx,[arr objectAtIndex:idx]);
        }];
        
        //第二种
        dispatch_apply([arr count], dispatch_get_global_queue(0, 0), ^(size_t index){//并行
            NSLog(@"%ld,%@",index,[arr objectAtIndex:index]);
        });
        
        //第三种
        dispatch_apply([arr count], dispatch_get_main_queue(), ^(size_t index){//串行,容易引起主线程堵塞,可以另外开辟线程
            NSLog(@"%ld,%@",index,[arr objectAtIndex:index]);
        });
        
        // 第四种,快速遍历
        for (NSString * str in arr) {
            NSLog(@"%@",str);
        }
        
        // 第五种,do-while
        int i = 0;
        do {
            NSLog(@"%@",[arr objectAtIndex:i]);
            i++;
        } while (i<[arr count]);
        
        // 第六种,while-do
        int j = 0;
        while (j<[arr count]) {
            NSLog(@"%@",[arr objectAtIndex:j]);
            j++;
        }
        
        // 第七种,普通for循环
        for (int m = 0; m<[arr count]; m++) {
            NSLog(@"%@",[arr objectAtIndex:m]);
        }
    
        // 第八种,迭代器
        NSEnumerator *en = [arr objectEnumerator];
        id obj;
        NSInteger j = 0 ;
        while (obj = [en nextObject]) {
            NSLog(@"%ld,%@",j,obj);
            j++;
        }

        个人比较常用普通的for循环或forin快速遍历,可能其他方法更好,以后我还需多多尝试。

      注意:

      ① 其中第二种方法由于是并行,所以打印出来的东西是随机的,并不是按照顺序打印的。

      ② 第三种容易引起主线程堵塞,所以最好自己另外创建一个线程。

  • 相关阅读:
    ios英语口语800句应用源码
    乐够GO应用源码完整版
    学生信息管理系统应用ios源码iPad版
    安卓版蝌蚪播放器客户端应用源码完整版
    一个Brushes笔画应用ios源码完整版
    模仿百度卫士应用最新版源码下载
    高仿QQ的即时通讯应用带服务端软件安装
    较好的IOS新闻客户端应用源码
    中国科学报客户端应用源码
    二叉树基础操作
  • 原文地址:https://www.cnblogs.com/ljios/p/4692128.html
Copyright © 2011-2022 走看看