Blocks

如下,定义一个block:

blocks

使用之:

printf(“%d”, myBlock(3));//prints “21”

 

也可以直接在使用block:

char *myCharacters[3] = {“TomJohn”, “George”, “Charles Condomine”};

qsort_b(myCharacters, 3, sizeof(char *), ^(const void *l, const void *r){

char *left = *(char **)l;

char *right =*(char **)r;

return strncmp(left, right, 1);

});

 

Usage

Blocks represent typically small, self-contained pieces of code. As such, they’re particularly useful as a means of encapsulating units of work that may be executed concurrently, or over items in a collection, or as a callback when another operation has finished.

Blocks are a useful alternative to traditional callback functions for two main reasons:

1. They allow you to write code at the point of invocation that is executed later in the context of the method implementation.
Blocks are thus often parameters of framework methods.

2. They allow access to local variables.
Rather than using callbacks requiring a data structure that embodies all the contextual information you need to perform an operation, you simply access local variables directly.

 

声明一个block

声明一个block,就像声明一个c函数指针一样:

void (^blockReturningVoidWithVoidArgument)(void);

int (^blockReturningIntWithIntAndCharArguments)(int, char);

void (^arrayOfThenBlocksReturningVoidWithIntArgument[10])(int);

 

当然也可以typedef block,然后多地使用:

typedef float (^MyBlockType)(float, float);

 

MyBlockType myFirstBlock = //…;

MyBlockType mySecondBlock = //…;

 

编写一个block

int (^oneForm)(int);

 

oneForm = ^(int anInt){return anInt –1;};

 

定义全局block

文件的级别,可以定义一个全局的block:

#import <stdio.h>

 

int GlobalInt = 0;

int (^getGlobalInt)(void) = ^{ return GlobalInt;};

 

变量和block

在语义范围内定义的局部变量,在block内,将会当作const来对待,如果想要修改这个变量值,则需要用__block修饰。

__block和register, auto, static类似,但是是互相排斥的。

example:

extern NSInteger CounterGlobal;

static NSInteger CounterStatic;

 

{

NSInteger localCounter = 42;

__block char localCharacter;

void (^aBlock)(void) = ^(void){

      ++CounterGlobal;

      ++CounterStatic;

      CounterGlobal = localCounter;

      localCharacter = ‘a’;

};

++localCounter; //unseen by block

localCharacter = ‘b’;

aBlock();//execute the block

//localCharacter now ‘a’

}

 

Objective-C Objects  和 __block

If you use a block within the implementation of a method, the rules for memory management of object instance variables are more subtle:

1. If you access an instance variable by reference, self is retained;

2. If you access an instance variable by value, the variable is retained;

 

dispatch_async(queue, ^{

doSomethingWithObject(instanceVariable);// instanceVariable is used by reference, self is retained

});

 

id localVariable = instanceVariable;

dispatch_async(queue, ^{

doSomethingWithObject(localVariable); // localVariable is userd by value, localVariable is retained (not self)

});

posted @ 2012-06-05 19:59  agefisher  阅读(312)  评论(0编辑  收藏  举报