WWDC2010 Session206 介绍iPhone上的Blocks和Grand Central Dispatch (1)

Blocks和Grand Central Dispatch已经被iOS4支持,(Snow Leopard早就支持了).

程序运行架构

Technology Stack Block and Grand Central Dispatch

Blocks

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

Basic Blocks

我们在block中使用这个字符^ 因为这个字符很特别,在C++中不能作为操作符重载.

Block 词法

^ [返回类型][参数] { 内容 }

看起来就像一个没有名字的函数,前面加上^. 如果没有返回或者没有参数,可以把void省略。

Block Syntax

Blocks as Data

定义Block pointer. 看起来像函数pointer: void (*callable)(void);

void (^callable)(void);

下面这是一个复杂的block pointer,它的参数也是一个block pointer.

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

可以使用typedef来简化:

typedef BOOL (^doneBlk_t)(int);

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

Blocks实践

Work Block Consumer

定义一个repeat函数,参数一个block pointer:

typedef void (^workBlk_t)(int i);

void repeat(int n, workBlk_t aBlock) {

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

    aBlock(i);

}

定义一个 block然后调用repeat函数:

int d = 2;

workBlk_t w = ^(int i) {

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

};

repeat(5, w);

输出:

0

2

4

6

8

同步执行

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

  return [obj testValue: value];

}];

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

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

}];

Callbacks回调

有了block,我们可以直接定义callbacks,而不用去定义一个函数。这样会让代码简单点。

[application beginBackgroundTaskWithExpirationHandler: ^{

  /* expiration handler callback code */

}];

[anOperation setCompletionBlock: ^{

  /* handle operation completion */

}];

异步执行

[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详情

Block Object Details

1. Blocks(竟然)是Objective-C的一个对象

2. Block生成与栈上 (因为在栈上生成会很快)

- 可以用[aBlock copy] or Block_copy()复制到heap中 (相对代价大)

- 释放[aBlock release] or Block_release() (必须手动释放heap中的block)

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

- Shared with the scope of declaration

- __block Object references are not retained

Block lifetime illustrated

1. Start on stack and capture state


Block lifetime 1

2. Copies state to heap
Block lifetime2

3. block1 and block2/3 could finish first. No sequence.


posted on 2011-04-06 16:03  VinceOniPhone  阅读(1472)  评论(0编辑  收藏  举报

导航