数组的五种遍历
首先定义一个数组,并获取数组长度
NSArray *array=@[@"1",@"2",@"3",@"4",@"5",@"6",@"7",@"8",@"9",];
NSInteger count =array.count;
一、for循环
for (NSInteger i=0; i NSLog(@"%@----%@",array[i],[NSThread currentThread]); } 打印结果如下: 1 2 3 4 。。。。 二、for in 快速枚举 for (NSString *string in array) { NSLog(@"%@----%@",string,[NSThread currentThread]); } 打印结果如下: 2017-01-03 11:04:01.990 MyTestWorkProduct[2086:78292] 1---- 2017-01-03 11:04:01.990 MyTestWorkProduct[2086:78292] 2---- 2017-01-03 11:04:01.991 MyTestWorkProduct[2086:78292] 3---- 2017-01-03 11:04:01.992 MyTestWorkProduct[2086:78292] 4---- 2017-01-03 11:04:01.992 MyTestWorkProduct[2086:78292] 5---- 2017-01-03 11:04:01.993 MyTestWorkProduct[2086:78292] 6---- 2017-01-03 11:04:01.993 MyTestWorkProduct[2086:78292] 7---- 2017-01-03 11:04:01.993 MyTestWorkProduct[2086:78292] 8---- 2017-01-03 11:04:01.994 MyTestWorkProduct[2086:78292] 9---- 2017-01-03 11:04:01.994 MyTestWorkProduct[2086:78292] end 三、NSEnumerator NSEnumerator *enumer=[array objectEnumerator]; id obj; while (obj=[enumer nextObject]) { NSLog(@"%@----%@",obj,[NSThread currentThread]); } 打印结果如下: 2017-01-03 11:05:37.138 MyTestWorkProduct[2156:79788] 1---- 2017-01-03 11:05:37.139 MyTestWorkProduct[2156:79788] 2---- 2017-01-03 11:05:37.140 MyTestWorkProduct[2156:79788] 3---- 2017-01-03 11:05:37.140 MyTestWorkProduct[2156:79788] 4---- 2017-01-03 11:05:37.140 MyTestWorkProduct[2156:79788] 5---- 2017-01-03 11:05:37.141 MyTestWorkProduct[2156:79788] 6---- 2017-01-03 11:05:37.141 MyTestWorkProduct[2156:79788] 7---- 2017-01-03 11:05:37.141 MyTestWorkProduct[2156:79788] 8---- 2017-01-03 11:05:37.142 MyTestWorkProduct[2156:79788] 9---- 2017-01-03 11:05:37.142 MyTestWorkProduct[2156:79788] end 四、快速遍历 //顺序遍历 [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]); }]; 打印结果如下: 1 2 3 4 ..... 4 3 2 1 五、快速迭代 //将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"); 打印结果如下: 1 7 6 8 1 1 7 6 8 1 根据打印结果最后才打印 end 字符可知,dispatch_apply会等待每个block中的任务都执行完成后,才往下执行。 总结:从这五种遍历方式来看,第5种采用的多线程,对于处理耗时的数组遍历比较适用。