iOS多线程学习小记『GCD的API之dispatch_appl

2018-07-25  本文已影响17人  达若漠沙

3.2.9 dispatch_apply

dispatch_apply 函数是dispatch_async函数和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");

2
1
0
3
6
5
4
7
8
9
done

    NSArray * array = @[@"001",@"002",@"003"];
    dispatch_apply([array count], queue, ^(size_t index) {
        NSLog(@"123   %zu:%@",index,[array objectAtIndex:index]);
    });

这样可简单地在Global Dispatch Queue中对所有的元素执行Block.

另外,由于dispatch_apply函数也与dispatch_sync函数相同,会等待处理执行结束,因此推荐在dispatch_async函数中非同步地执行dispatch_apply函数

    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    NSArray * array = @[@"001",@"002",@"003"];
    dispatch_async(queue, ^{

        dispatch_apply([array count], queue, ^(size_t index) {
            NSLog(@"%zu:%@",index,[array objectAtIndex:index]);
        });
    });

    //回到主线程
    dispatch_async(dispatch_get_main_queue(), ^{
        NSLog(@"done");
    });
上一篇下一篇

猜你喜欢

热点阅读