GCD中的dispatch_apply的用法及作用
1. dispatch_apply的基本用法
官方文档:
Submits a block to a dispatch queue for parallel invocation. This function waits for the task block to complete before returning. If the specified queue is concurrent, the block may be invoked concurrently, and it must therefore be reentrant safe.
意思是dispatch_apply函数是dispatch_sync函数和Dispatch Group的关联API,该函数按指定的次数将指定的Block追加到指定的Dispatch Queue中,并等到全部的处理执行结束
1 | void dispatch_apply(size_t iterations, dispatch_queue_t queue,DISPATCH_NOESCAPE void (^block)(size_t)); |
其中:
iterations,要执行的迭代次数。
queue,提交块的调度队列,要传递的首选值是DISPATCH_APPLY_AUTO,以便自动使用适合调用线程的队列。
block,要调用的块的迭代次数指定,为了按执行顺序区分各个Block。
2. dispatch_apply使用
(一)实现for循环1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25- (void)test{
NSArray *array = @[@"1",@"2",@"3",@"4",@"5",@"6",@"7",@"8",@"9",@"10"];
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_apply(array.count, queue, ^(size_t index) {
NSLog(@"%zu:%@",index,array[index]);
});
NSLog(@"over");
/*
输出结果:
[83613:5550032] 0:1
[83613:5550032] 1:2
[83613:5550032] 2:3
[83613:5550131] 4:5
[83613:5550032] 3:4
[83613:5550131] 5:6
[83613:5550131] 6:7
[83613:5550131] 8:9
[83613:5550131] 9:10
[83613:5550136] 7:8
[83613:5550032] over
因为dispatch_apply是在global_queue中执行,所以每个处理的时间不确定,但是over肯定是最后执行,因为dispatch_apply会等待所有的处理结果
*/
}
3.在dispatch_async中异步执行dispatch_apply,模拟同步效果
1 | - (void)test{ |