6.4. Dispatching Tasks to Grand Central Dispatch

Problem

You want to learn how to create a block of code that can be executed by GCD.

Solution

There are two ways to submit tasks to dispatch queues:

Discussion

Block objects are the best way of utilizing GCD and its enormous power. Some GCD functions have been extended to allow programmers to use C functions instead of block objects. However, the truth is that only a limited set of GCD functions allow programmers to use C functions, so please do read the recipe about block objects (Recipe 6.1) before proceeding any further.

C functions that have to be supplied to various GCD functions should be of type dispatch_function_t, which is defined as follows in the Apple libraries:

typedef void (*dispatch_function_t)(void *);

So if we want to create a function named, for instance, myGCDFunction, we would have to implement it in this way:

void myGCDFunction(void * paraContext){

  /* Do the work here */

}

Note

The paraContext parameter refers to the context that GCD allows programmers to pass to their C functions when they dispatch tasks to them. We will learn about this shortly.

Block objects that get passed to GCD functions don’t always follow the same structure. Some must accept parameters and some shouldn’t, but none of the block objects submitted to GCD return a value.

In the next three sections, you will learn how to submit tasks to GCD for execution whether they are in the form of block objects or C functions. ...

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.