美文网首页
iOS【数组常用的五种遍历方式】

iOS【数组常用的五种遍历方式】

作者: NJ_墨 | 来源:发表于2018-02-26 15:22 被阅读18次

    一、for循环

    for (NSInteger i=0; i<count; i++) {
       NSLog(@"%@----%@",array[i],[NSThread currentThread]);
    }
    

    二、forin 快速枚举

    for (NSString *string in array) {
            NSLog(@"%@----%@",string,[NSThread currentThread]);
     }
    

    三、NSEnumerator

    NSEnumerator *enumer=[array objectEnumerator];
    id obj;
    while (obj=[enumer nextObject]) {
        NSLog(@"%@----%@",obj,[NSThread currentThread]);
    }
    

    四、快速遍历

    //顺序遍历
    [array enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        NSLog(@"%@----%@",array[idx],[NSThread currentThread]);
    }];
    //倒序遍历    
    [array enumerateObjectsWithOptions:NSEnumerationReverse usingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        NSLog(@"%@----%@",array[idx],[NSThread currentThread]);    
    }];
    

    五、快速迭代

    //将block中的任务,逐个放到queue中,然后进行dispatch_sync执行
    //多线程同步循环
        
    dispatch_queue_t queue =dispatch_queue_create("apply并行队列", DISPATCH_QUEUE_CONCURRENT);
    dispatch_apply(count, queue, ^(size_t index) {
            NSLog(@"%@----%@",array[index],[NSThread currentThread]);    
    });
    NSLog(@"end");
    

    总结:从这五种遍历方式来看,第5种采用的多线程,对于处理耗时的数组遍历比较适用。

    相关文章

      网友评论

          本文标题:iOS【数组常用的五种遍历方式】

          本文链接:https://www.haomeiwen.com/subject/fpsyxftx.html