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快速遍历,可能其他方法更好,以后我还需多多尝试。

      注意:

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

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

  • 相关阅读:
    我的2019,探索在路上
    深度学习-TensorFlow2.0笔记(一)
    机器学习笔记(二)
    机器学习笔记(一)
    SQL注入分类以及联合查询回显注入
    数据库基础概念
    SQL注入原理、常见思路之Access手工注入实战
    OWASP top 10 2017
    HTTP协议及burp基本使用
    web系统架构
  • 原文地址:https://www.cnblogs.com/ljios/p/4692128.html
Copyright © 2011-2022 走看看