dispatch_apply

作用:

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");
});

你可能感兴趣的:(dispatch_apply)