6.7. Executing Non-UI Related Tasks Asynchronously with GCD
Problem
You want to be able to execute non-UI related tasks asynchronously, with the help of GCD.
Solution
This is where GCD can show its true power: executing blocks of code asynchronously on the main, serial, or concurrent queues. I promise that, by the end of this section, you will be completely convinced GCD is the future of multithread applications, completely replacing threads in modern apps.
In order to execute asynchronous tasks on a dispatch queue, you must use one of these functions:
dispatch_async
Submits a block object to a dispatch queue (both specified by parameters) for asynchronous execution.
dispatch_async_f
Submits a C function to a dispatch queue, along with a context reference (all three specified by parameters), for asynchronous execution.
Discussion
Let’s have a look at a real example. We’ll write an iOS app that is able to download an image from a URL on the Internet. After the download is finished, the app should display the image to the user. Here is the plan and how we will use what we’ve learned so far about GCD in order to accomplish it:
We are going to launch a block object asynchronously on a concurrent queue.
Once in this block, we will launch another block object synchronously, using the
dispatch_sync
function, to download the image from a URL. We do this because we want the rest of the code in this concurrent queue to wait until the image is downloaded. Therefore, we are only making the concurrent queue ...
Get iOS 6 Programming Cookbook now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.