引用如果想在dispatch_queue中所有的任務執行完成后在做某種操作,在串行隊列中,可以把該操作放到最后一個任務執行完成后繼續,但是在并行隊列中怎么做呢。這就有dispatch_group 成組操作。
Grouping blocks allows for aggregate synchronization. Your application can submit multiple blocks and track when they all complete, even though they might run on different queues. This behavior can be helpful when progress can’t be made until all of the specified tasks are complete.
打包blocks允許 集合同步操作.程序可以提交多個不同的blocks并且跟蹤直到他們執行結束.即使這些被提交到不同的隊列上,也可以.
dispatch_group_async
文檔注釋:Submits a block to a dispatch queue and associates the block with the specified dispatch group.
dispatch_queue_t dispatchQueue = dispatch_queue_create("ted.queue.next", DISPATCH_QUEUE_CONCURRENT);
dispatch_group_t dispatchGroup = dispatch_group_create();
dispatch_group_async(dispatchGroup, dispatchQueue, ^(){
NSLog(@"dispatch-1");
});
dispatch_group_async(dispatchGroup, dispatchQueue, ^(){
NSLog(@"dspatch-2");
});
dispatch_group_notify(dispatchGroup, dispatch_get_main_queue(), ^(){
NSLog(@"end");
});
上面的 log1 和log2輸出順序不定,因為是在并發隊列上執行,當并發隊列全部執行完成后,最后到main隊列上執行一個操作,保證“end”是最后輸出。 另外,這里也可以不用創建自己的并發隊列,用全局的global,那個也是個并發隊列. dispatch_get_gloable_queue(0,0);
這里就需要介紹下dispatch_group_notify
文檔注釋:Schedules a block object to be submitted to a queue when a group of previously submitted block objects have completed.
提交一個預準備的代碼塊到一個隊里,當一組之前提交的block執行完成后,觸發.
參考上面的代碼就好理解了.
Discussion 具體書名
This function schedules a notification block to be submitted to the specified queue when all blocks associated with the dispatch group have completed. If the group is empty (no block objects are associated with the dispatch group), the notification block object is submitted immediately.
這個方法 實現了一個通知一個指定執行的隊列blcok,當這組中所有的blocks執行完成以后,會被通知執行.
當這組的block是空的,那么這個通知的block也會立即觸發.
When the notification block is submitted, the group is empty. The group can either be released with dispatch_release or be reused for additional block objects. See dispatch_group_async for more information.
當這個通知的block被提交,這個 組也是空的,那么這個組 既可以手動釋放,也可以 被添加的block對象重用.