6.7. Executing Non-UI Related Tasks Asynchronously with GCD
You want to be able to execute non-UI related tasks asynchronously, with the help of GCD.
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:
Submits a block object to a dispatch queue (both specified by parameters) for asynchronous execution.
Submits a C function to a dispatch queue, along with a context reference (all three specified by parameters), for asynchronous execution.
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_syncfunction, 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 ...