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

2018-02-26  本文已影响18人  NJ_墨

一、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种采用的多线程,对于处理耗时的数组遍历比较适用。

上一篇下一篇

猜你喜欢

热点阅读