I read the following Apple documentation on the completion block in dispatch queues, and it's hard for me to understand part of it. The document mentions that "In order to prevent the queue from prematurely being released, it is important to first keep this queue and empty it after the completion block is sent." This contradicts my understanding that a block stores all the variables in its closure, which is mentioned in the Block Programming Guide.
What am I missing here? The following is a snippet of the document:
A completion block is another piece of code that you queue at the end of your original task. The calling code usually provides a completion block as a parameter when the task starts. All the task code must do is send the specified block or function to the specified queue when it completes its work.
Listing 3-4 shows the averaging function implemented using blocks. The last two parameters for the averaging function allow the caller to specify the queue and block for use in presenting the results. After the averaging function calculates its value, it passes the results to the specified block and sends it to the queue. To prevent the queue from being released prematurely, it is essential that you first save the queue and release it after the completion block is sent. Listing 3-4 Completing the completion callback after a task
void average_async(int *data, size_t len, dispatch_queue_t queue, void (^block)(int))
{
dispatch_retain(queue);
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
int avg = average(data, len);
dispatch_async(queue, ^{ block(avg);});
dispatch_release(queue);
});
}
source
share