我的建議是使用dispatch_group
。致電dispatch_async
之前致電dispatch_group_enter
,並致電dispatch_group_leave
,並由dispatch_async
執行該塊的結尾。然後,在將所有塊排入隊列之後,使用dispatch_group_notify
安排完成塊,該塊將在所有其他dispatch_async
塊完成後運行。
dispatch_group_t group = dispatch_group_create();
for (...) {
dispatch_group_enter(group);
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
...
dispatch_group_leave(group);
});
}
dispatch_group_notify(group, dispatch_get_main_queue(), ^{
// This gets called when all the other blocks have finished
});
或者,你可以使用一個NSOperationQueue
代替libdispatch,並完成操作,其中列出所有其他操作的依賴。但是,這有一個缺點,即完成操作不會在主隊列上執行。
NSOperation *completionOperation = [NSBlockOperation blockOperationWithBlock:^{
// This gets called when all the other operations have finished
}];
for (...) {
NSOperation *operation = [NSBlockOperation blockOperationWithBlock:^{
...
}];
[completionOperation addDependency:operation];
[operationQueue addOperation:operation];
}
[operationQueue addOperation:completionOperation];
你想等待最後一次做什麼呼叫或你是什麼意思。我害怕我根本沒有得到它 –
[在佈局子視圖中實現Cocoa Touch中的去抖整合模式](https://stackoverflow.com/q/28153632) –