今天我們來(lái)說(shuō)說(shuō)dispatch_group在開(kāi)發(fā)過(guò)程中的應(yīng)用。
- 我決定每篇文章的開(kāi)頭都會(huì)放上福利掷漱。
![0QE1_)${@(K3]~HO]@HT]E5.jpg](http://upload-images.jianshu.io/upload_images/1436009-b226ccaab07aac58.jpg?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
在實(shí)際開(kāi)發(fā)中我們會(huì)遇到這樣一種需求:某個(gè)頁(yè)面加載時(shí)通過(guò)網(wǎng)絡(luò)請(qǐng)求獲得相應(yīng)的數(shù)據(jù)卜范,再做某些操作海雪,有時(shí)候加載的內(nèi)容需要通過(guò)好幾個(gè)接口的數(shù)據(jù)組合而成舱殿,比如有兩個(gè)請(qǐng)求A和B,我們通常為了省事湾宙,會(huì)將B請(qǐng)求放在A請(qǐng)求成功的回調(diào)中發(fā)起侠鳄,在B的成功回調(diào)中將數(shù)據(jù)組合起來(lái)死宣,這樣做有明顯的問(wèn)題:
- 請(qǐng)求如果多了十电,需要寫(xiě)許多嵌套的請(qǐng)求
- 如果在除了最后一個(gè)請(qǐng)求前的某個(gè)請(qǐng)求失敗了,就不會(huì)執(zhí)行后面的請(qǐng)求台盯,數(shù)據(jù)無(wú)法加載
- 請(qǐng)求變成同步的静盅,這是最大的問(wèn)題寝殴,在網(wǎng)絡(luò)差的情況下,如果有n個(gè)請(qǐng)求市咽,意味著用戶(hù)要等待n倍于并發(fā)請(qǐng)求的時(shí)間才能看到內(nèi)容施绎。
接下來(lái)我們就來(lái)解決這個(gè)問(wèn)題。
dispatch_group_wait
dispatch_group_wait會(huì)同步地等待group中所有的block執(zhí)行完畢后才繼續(xù)執(zhí)行
NSLog(@"第一個(gè)執(zhí)行");
// 創(chuàng)建一個(gè)group
dispatch_queue_t queue = dispatch_queue_create("queue", DISPATCH_QUEUE_CONCURRENT);
dispatch_group_t group = dispatch_group_create();
dispatch_group_async(group,queue,^{
NSLog(@"線(xiàn)程1");
});
dispatch_group_async(group,queue,^{
NSLog(@"線(xiàn)程2");
});
dispatch_group_wait(group,DISPATCH_TIME_FOREVER);
NSLog(@"走后執(zhí)行");
執(zhí)行結(jié)果
dispatch_queue_t queue = dispatch_queue_create("queue", DISPATCH_QUEUE_CONCURRENT);
dispatch_group_t group = dispatch_group_create();
dispatch_group_async(group,queue,^{
NSLog(@"線(xiàn)程一");
});
dispatch_group_async(group,queue,^{
NSLog(@"線(xiàn)程二");
});
dispatch_group_notify(group, dispatch_get_main_queue(), ^{
NSLog(@"一和二完成");
});
NSLog(@"異步執(zhí)行");
執(zhí)行結(jié)果
dispatch_group_enter dispatch_group_leave
// 創(chuàng)建一個(gè)group
dispatch_group_t group = dispatch_group_create();
dispatch_queue_t queue = dispatch_queue_create("queue", DISPATCH_QUEUE_CONCURRENT);
dispatch_group_enter(group);
dispatch_async(queue, ^{
NSLog(@"線(xiàn)程一");
dispatch_group_leave(group);
});
dispatch_group_enter(group);
dispatch_async(queue, ^{
NSLog(@"線(xiàn)程二");
dispatch_group_leave(group);
});
//等待group完成所有異步操作
dispatch_group_notify(group, dispatch_get_main_queue(), ^{
NSLog(@"一二倆個(gè)執(zhí)行完最后走");
});
NSLog(@"異步執(zhí)行");
執(zhí)行結(jié)果
// 下面兩種方法是相同的 沒(méi)發(fā)現(xiàn)什么區(qū)別
dispatch_group_async(group, queue, ^{
});
dispatch_group_enter(group);dispatch_async(queue, ^{
dispatch_group_leave(group);
});