Cover by Vandad Nahavandipoor

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

O'Reilly logo

5.7. Performing 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:

  1. We are going to launch a block object asynchronously on a concurrent queue.

  2. 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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required