5.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_asyncfunctionExecutes a block object on a dispatch queue.
dispatch_async_ffunctionExecutes 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" ...Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access