OC-多线程任务完成后统一处理

//MARK:网络请求 - (void)loadData:(void(^)(void))action { action(); // 回调不管成功或者失败都回调 }

1.信号量
dispatch_semaphore_t semaphore = dispatch_semaphore_create(0); dispatch_group_t group = dispatch_group_create(); dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0); __weak typeof(self) weakself = self; [HUDManage showLoadingHUD]; dispatch_group_async(group, queue, ^{ [weakself loadData1:^{ // 请求完成,可以通知界面刷新界面等操作 NSLog(@"第一步网络请求完成"); // 使信号的信号量+1,这里的信号量本来为0,+1信号量为1(绿灯) dispatch_semaphore_signal(semaphore); }]; // 以下还要进行一些其他的耗时操作 NSLog(@"耗时操作继续进行"); dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER); }); dispatch_group_async(group, queue, ^{ [weakself loadData2:^{ // 请求完成,可以通知界面刷新界面等操作 NSLog(@"第二步网络请求完成"); // 使信号的信号量+1,这里的信号量本来为0,+1信号量为1(绿灯) dispatch_semaphore_signal(semaphore); }]; // 以下还要进行一些其他的耗时操作 NSLog(@"耗时操作继续进行"); dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER); }); dispatch_group_notify(group, dispatch_get_main_queue(), ^{ NSLog(@"刷新界面等在主线程的操作"); });

【OC-多线程任务完成后统一处理】2.group组
__weak typeof(self) weakself = self; dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0); dispatch_group_t group = dispatch_group_create(); //创建group dispatch_group_enter(group); //进入group dispatch_group_async(group, queue, ^{ [weakself loadData1:^{ dispatch_group_leave(group); //离开group }]; }); dispatch_group_enter(group); //进入group dispatch_group_async(group, queue, ^{ [weakself loadData2:^{ dispatch_group_leave(group); //离开group }]; }); // 等待通知 dispatch_group_notify(group, dispatch_get_main_queue(), ^{ NSLog(@"刷新界面等在主线程的操作"); });

    推荐阅读