之前已經介紹了dispatch_semaphore的底層實現,dispatch_group的實現是基於前者的。在看源碼之前,我們先看一下我們是如何應用的。假設有這麼場景:有一個A耗時操作,B和C兩個網路請求和一個耗時操作C當ABC都執行完成後,刷新頁面。我們可以用dispatch_group實現。
dispatch關鍵如下:
-(void)viewDidLoad{
[superviewDidLoad];
__blockNSIntegernumber=0;
dispatch_group_tgroup=dispatch_group_create();
//A耗時操作
dispatch_group_async(group,dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,0),^{
sleep(3);
number+=2222;
});
dispatch的代碼
//B網路請求
dispatch_group_enter(group);
[selfsendRequestWithCompletion:^(idresponse){
number+=[responseintegerValue];
dispatch_group_leave(group);
}];
//C網路請求
dispatch_group_enter(group);
[selfsendRequestWithCompletion:^(idresponse){
number+=[responseintegerValue];
dispatch_group_leave(group);
}];
dispatch_group_notify(group,dispatch_get_main_queue(),^{
NSLog(@"%zd",number);
});
}
-(void)sendRequestWithCompletion:(void(^)(idresponse))completion{
//模擬一個網路請求
dispatch_queue_tqueue=dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,0);
dispatch_async(queue,^{
sleep(2);
dispatch_async(dispatch_get_main_queue(),^{
if(completion)completion(@1111);
});
});
}
總之,dispatch給大家簡單的介紹了一些,希望大家多看看。