需求: 三個并發(fā)的網(wǎng)絡(luò)請求,都完成之后,更新UI
實現(xiàn):利用dispatch group 的dispatch_group_enter(group)和 dispatch_group_leave(group)確保每個任務(wù)的完成潮酒,即使某個任務(wù)是異步的,在所有任務(wù)都完成后再執(zhí)行notify中的代碼
代碼:
dispatch_group_t upload_group = dispatch_group_create();
// 并行隊列
dispatch_queue_t upload_queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,0);
// 進(jìn)入組和離開組必須成對出現(xiàn),否則會造成死鎖
dispatch_group_enter(upload_group);// 進(jìn)入組
dispatch_group_async(upload_group, upload_queue, ^{
// 任務(wù)1
dispatch_group_leave(upload_group);// 完成之后離開組
});
dispatch_group_enter(upload_group);// 進(jìn)入組
dispatch_group_async(upload_group, upload_queue, ^{
// 任務(wù)2
dispatch_group_leave(upload_group);// 完成之后離開組
});
dispatch_group_notify(upload_group, dispatch_get_main_queue(), ^{
// 完成
});