Wednesday, April 06, 2011

WWDC2010 Session206 Introducing Blocks and Grand Central Dispatch (1)

Blocks and Grand Central Dispatch are available on iOS4, and have been available on Snow Leopard.

Technology Stack

Technology Stack Block and Grand Central Dispatch  


Blacks are available in C++ and Objective-C++.

Basic Blocks

We will use ^ for blocks because this character is unique and could not be used as operator in C++.

Block Literal Syntax

^ [Return type][Arguments] { Body }

Just looks like a function without function name starting with ^. If no return or no arguments, void could be skipped.

Block Syntax

Blocks as Data

We can define Block pointer. It looks like a function pointer: void (*callable)(void);

void (^callable)(void);

This is an ugly block pointer whose argument is also a block pointer.

char *(^worker)(char *a, BOOL(^done)(int));

We can use typedef to simplify it just like what we do for function pointers:

typedef BOOL (^doneBlk_t)(int);

char *(^workB)(char *a, doneBlk_t d);

Blocks in Practice

Work Block Consumer

Define a repeat function with a block argument:

typedef void (^workBlk_t)(int i);

void repeat(int n, workBlk_t aBlock) {

  for (int i = 0; i < n; ++i)



Define a block and call the repeat function:

int d = 2;

workBlk_t w = ^(int i) {

  printf(“%d\n”, i * d);


repeat(5, w);

The output is:






Synchronous Execution

[mySet objectsPassingTest: ^(id obj, BOOL *stop) {

  return [obj testValue: value];


[aDictionary enumerateKeysAndObjectsUsingBlock: ^(id k, id v, BOOL *stop) {

  NSLog(@”%@ => %@”, k, v);



With block, we can define the callbacks directly, need not define a new function. It will make code simpler.

[application beginBackgroundTaskWithExpirationHandler: ^{

  /* expiration handler callback code */


[anOperation setCompletionBlock: ^{

  /* handle operation completion */


Asynchronous Execution

[operationQueue addOperationWithBlock: ^{

  /* hard work is hard */


dispatch_async(main_queue, ^{

  [viewController displayNewStuff];


Lockless exclusion

// thread a

dispatch_async(queue, ^{ … });

// thread b

dispatch_async(queue, ^{ … });

// main thread

dispatch_async(queue, ^{ … });

Blocks in Detail

Block Object Details

1. Blocks are Objective-C objects

2. Block objects start out on the stack (because objects allocate on stack very fast)

- Copied to the heap using [aBlock copy] or Block_copy() (relatively expensive)

- Release with [aBlock release] or Block_release() (you need to manually release the block on heap.)

3. Blocks have private const copy of stack (auto) variables

- Object references are retained.

4. Mutable variables must be declared with __block keyword

- Shared with all other blocks that use that variable

No comments: