dispatch_group
dispatch_group最常见的功能就是,进入一个页面有多个网络请求,我们想在所有的请求完成后再进行UI的刷新。
代码:
- (void)test_dispatch_group {
dispatch_group_t group = dispatch_group_create();
dispatch_queue_t queue = dispatch_queue_create("com.jueyingxx.concurrent_queue", DISPATCH_QUEUE_CONCURRENT);
dispatch_group_enter(group);
dispatch_async(queue, ^{
NSLog(@"task 1");
dispatch_group_leave(group);
});
dispatch_group_enter(group);
dispatch_async(queue, ^{
NSLog(@"task 2");
dispatch_group_leave(group);
});
dispatch_group_enter(group);
dispatch_async(queue, ^{
NSLog(@"task 3");
dispatch_group_leave(group);
});
dispatch_group_enter(group);
dispatch_async(queue, ^{
NSLog(@"task 4");
dispatch_group_leave(group);
});
dispatch_group_notify(group, dispatch_get_main_queue(), ^{
NSLog(@"main task");
});
}
输出结果:
2016-11-04 10:19:41.685 GCD_Demo[64555:1619028] task 4
2016-11-04 10:19:41.685 GCD_Demo[64555:1619026] task 2
2016-11-04 10:19:41.685 GCD_Demo[64555:1619025] task 1
2016-11-04 10:19:41.685 GCD_Demo[64555:1619034] task 3
2016-11-04 10:19:41.689 GCD_Demo[64555:1619002] main task
结论:
1、task1234任务是随机执行的。
2、main task总会在task1234全部完成后执行,符合我们的预期
3、这种做法就是前面的任务都是并发执行的,最后我们回调主线程,做一些我们需要做的事,比如tableview的reloaddata。
网友评论