O'Reilly logo

iOS 6 Programming Cookbook 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

6.5. Performing UI-Related Tasks with GCD

Problem

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

Solution

Use the dispatch_get_main_queue function.

Discussion

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.

Note

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!"
                             delegate:nil                    
                    cancelButtonTitle:@"OK"
                    

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