作用:
dispatch_apply函數是dispatch_sync函數和Dispatch Group的關聯API
該函數按指定的次數將指定的Block追加到指定的Dispatch Queue中,并等到全部的處理執行結束
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_apply(10, queue, ^(size_t index) {
NSLog(@"%zu", index);
});
NSLog(@"done");
打印結果
2016-08-20 20:58:24.493 GCDDemo[8434:1001513] 0
2016-08-20 20:58:24.493 GCDDemo[8434:1001579] 1
2016-08-20 20:58:24.493 GCDDemo[8434:1001554] 2
2016-08-20 20:58:24.494 GCDDemo[8434:1001513] 4
2016-08-20 20:58:24.493 GCDDemo[8434:1001556] 3
2016-08-20 20:58:24.494 GCDDemo[8434:1001579] 5
2016-08-20 20:58:24.589 GCDDemo[8434:1001513] 7
2016-08-20 20:58:24.589 GCDDemo[8434:1001556] 8
2016-08-20 20:58:24.589 GCDDemo[8434:1001554] 6
2016-08-20 20:58:24.589 GCDDemo[8434:1001579] 9
2016-08-20 20:58:24.589 GCDDemo[8434:1001513] done
因為在Global Dispatch Queue中執行,所以各個處理的執行時間不定
39 但done一定會輸出在最后的位置,因為dispatch_apply函數會等待所以的處理結束(dispatch_sync函數阻塞住當前線程);
參數
第一個參數為重復次數,第二個參數為追加對象的Dispatch Queue,第三個參數為追加的處理。第三個參數的Block帶有參數,是為了按第一個參數重復追加Block并區分各個Block而使用。
使用技巧 模擬for循環:
NSArray *array = @[@"a", @"b", @"c", @"d", @"e", @"f", @"g", @"h", @"i", @"j"];
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_apply([array count], queue, ^(size_t index) {
NSLog(@"%zu: %@", index, [array objectAtIndex:index]);
});
NSLog(@"done");
打印結果:
2016-08-20 20:55:05.029 GCDDemo[8410:997281] 0: a
2016-08-20 20:55:05.029 GCDDemo[8410:997341] 1: b
2016-08-20 20:55:05.029 GCDDemo[8410:997342] 2: c
2016-08-20 20:55:05.029 GCDDemo[8410:997344] 3: d
2016-08-20 20:55:05.029 GCDDemo[8410:997281] 4: e
2016-08-20 20:55:05.029 GCDDemo[8410:997341] 5: f
2016-08-20 20:55:05.030 GCDDemo[8410:997342] 6: g
2016-08-20 20:55:05.030 GCDDemo[8410:997344] 7: h
2016-08-20 20:55:05.030 GCDDemo[8410:997281] 8: i
2016-08-20 20:55:05.030 GCDDemo[8410:997341] 9: j
2016-08-20 20:55:05.030 GCDDemo[8410:997281] done
優化:
在dispatch_async函數中異步執行dispatch_apply函數,這樣不會阻塞住當前線程
代碼:
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_async(queue, ^{
// 在全局并發隊列中等待dispatch_apply函數中全部處理執行結束
dispatch_apply(10, queue, ^(size_t index) {
// 并列執行相關處理
NSLog(@"%zu", index);
});
// dispatch_apply函數中的處理全部執行結束
dispatch_async(dispatch_get_main_queue(), ^{
// 主線程中處理用戶界面更新等操作
});
NSLog(@"done");
});