6.5. Performing UI-Related Tasks with GCD


You are using GCD for concurrency and you would like to know what the best way of working with UI-related APIs is.


Use the dispatch_get_main_queue function.


UI-related tasks have to be performed on the main thread, so the main queue is the only candidate for UI task execution in GCD. We can use the dispatch_get_main_queue function to get the handle to the main dispatch queue.

There are two ways of dispatching tasks to the main queue. Both are asynchronous, letting your program continue even when the task is not yet executed:

dispatch_async function

Executes a block object on a dispatch queue.

dispatch_async_f function

Executes a C function on a dispatch queue.


The dispatch_sync method cannot be called on the main queue because it will block the thread indefinitely and cause your application to deadlock. All tasks submitted to the main queue through GCD must be submitted asynchronously.

Let’s have a look at using the dispatch_async function. It accepts two parameters:

Dispatch queue handle

The dispatch queue on which the task has to be executed.

Block object

The block object to be sent to the dispatch queue for asynchronous execution.

Here is an example. This code will display an alert in iOS to the user, using the main queue:

dispatch_queue_t mainQueue = dispatch_get_main_queue();

dispatch_async(mainQueue, ^(void) {
  [[[UIAlertView alloc] initWithTitle:@"GCD"
                              message:@"GCD is amazing!"

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.