Usually dispatch_apply is a synchronous function, which will pause the current thread, then execute the block and return to the paused thread. See the following example
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");
The results is as followsBut this is a synchronous execution. Assume you have a NSMutableArray and you need to perform some action for each of the object in array asynchronously in a separate thread, this is how to do it. Also since this is executed in a global dispatch queue, you cannot guarantee which block runs first.
//first get a global dispatch queue
dispatch_queue_t queue = dispatch_get_global_queue (DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
//Then add an asynchronous block
dispatch_async(queue, ^{
//inside this block, you can use dispatch_apply
dispatch_apply([array count], queue, ^(size_t index) {
//your block code goes here.
});
//Now you block has finished. You can execute some other task here.
});
For any query, feel free to contact me via my linkedin profile.
