#import "ViewController.h" @interface ViewController () @end @implementation ViewController /** * disoatch group 是GCD的一項特性,可以把任務分組 */ - (void)viewDidLoad { [super viewDidLoad]; //一、建立 dispatch_group_t group = dispatch_group_create(); //任務編組的兩組方法 //一: void dispatch_group_async(dispatch_group_t group,dispatch_queue_t queue,dispatch_block_t block); //二: void dispatch_group_enter(dispatch_group_t group); void dispatch_group_leave(dispatch_group_t group); //用於等待dispatch group執行完畢 long dispatch_group_wait(dispatch_group_t group,dispatch_time_t timeout);//要等待的group,等待執行完畢時,阻塞時間 void dispatch_group_notify(dispatch_group_t group,dispatch_queue_t queue,dispatch_block_t block); //令數組中每一個對象都執行某項任務,而且想等待全部任務執行完畢。 dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0); dispatch_group_t dispatchGroup = dispatch_group_create(); NSArray *collection; for (id object in collection) { dispatch_group_async(dispatchGroup, queue, ^{ //object do task }); } dispatch_group_wait(dispatchGroup,DISPATCH_TIME_FOREVER);//直處處理完全部任務 //若當前線程不該阻塞,則用notify代替wait dispatch_queue_t notifyQueue = dispatch_get_main_queue(); dispatch_group_notify(dispatchGroup, notifyQueue, ^{ // block處理完全部任務 }); //把任務提交到併發隊列 dispatch_queue_t lowPriorityQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0); dispatch_queue_t highPriorityQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH,0); NSArray *lowPriorityQueueObjects; NSArray *highPriorityQueueObjects; for (id object in lowPriorityQueueObjects){ dispatch_group_async(dispatchGroup, lowPriorityQueue, ^{ // object perform task }); } for (id object in highPriorityQueueObjects){ dispatch_group_async(dispatchGroup, highPriorityQueue, ^{ //object perform task }); } dispatch_queue_t notifyQueue1 = dispatch_get_main_queue(); dispatch_group_notify(dispatchGroup, notifyQueue1, ^{ // }); //GCD方法實現,數組每一個元素執行任務 dispatch_queue_t queueGCD = dispatch_queue_create("www.queue", NULL); dispatch_apply(10, queueGCD, ^(size_t i) { //perform task }); //等效於 for (int i = 0; i<10;i++){ //perform task } } @end