GCD提供两种方式支持dispatch队列同步,即dispatch组和信号量。
一、dispatch组(dispatch group)
1. 创建dispatch组
dispatch_group_t group = dispatch_group_create();
2. 启动dispatch队列中的block关联到group中
dispatch_group_async(group, queue, ^{
});
3. 等待group关联的block执行完毕,也可以设置超时参数
dispatch_group_wait(group, DISPATCH_TIME_FOREVER);
4. 为group设置通知一个block,当group关联的block执行完毕后,就调用这个block。类似dispatch_barrier_async。
dispatch_group_notify(group, queue, ^{
});
5. 手动管理group关联的block的运行状态(或计数),进入和退出group次数必须匹配
dispatch_group_enter(group);
dispatch_group_leave(group);
例:
[selfstartLoading];
__block NSMutableArray* tmpStudentArray = [NSMutableArraynew];
dispatch_group_t group =dispatch_group_create();
for (NSInteger i=0;i<studentArray.count; i++)
{
dispatch_group_enter(group);
StudentEntity* student =studentArray[i];
NSMutableDictionary *dic = [NSMutableDictionarynew];
[dic setValue:teacherMessage.textforKey:TITLE];
[[Coding_NetAPIManagersharedManager] PublishComment:dicandBlock:^(id data,NSError *error){
dispatch_group_leave(group);
}];
}
dispatch_group_notify(group, dispatch_get_main_queue(), ^{
[selfstopLoading];
});