Block variables hold references to blocks. You declare them using syntax similar to that you use to declare a pointer to a function, except that you use ^
instead of *
. The block type fully interoperates with the rest of the C type system. The following are all valid block variable declarations:html
block變量維持了一個對block的引用。你聲明block使用了和聲明函數指針相同的語法,除了你使用「^」代替了「*」以外。block類型能夠和所有C類型系統相互操做。下列都是block變量的聲明:ios
void (^blockReturningVoidWithVoidArgument)(void); int (^blockReturningIntWithIntAndCharArguments)(int, char); void (^arrayOfTenBlocksReturningVoidWithIntArgument[10])(int);
Blocks also support variadic (...
) arguments. A block that takes no arguments must specify void
in the argument list.express
Blocks are designed to be fully type safe by giving the compiler a full set of metadata to use to validate use of blocks, parameters passed to blocks, and assignment of the return value. You can cast a block reference to a pointer of arbitrary type and vice versa. You cannot, however, dereference a block reference via the pointer dereference operator (*
)—thus a block's size cannot be computed at compile time.安全
You can also create types for blocks—doing so is generally considered to be best practice when you use a block with a given signature in multiple places:app
blocks 也支持可變參數。一個沒有參數的block必須在參數列表中指定void。
ide
blocks 被設計成對編譯器的徹底安全類型,它有一套完整的數據源設置來檢測block的合法性,經過傳給blocks參數,來分配返回值。你能夠給block建立任意的指針類型,反之亦然(PS:這句話,翻譯有疑問)。儘管如此,你不能經過解引用操做符(*)來解引用一個block——由於這樣在編譯的時候沒法計算block的大小。 函數
你也能夠建立block做爲類型,當你要在多個地方使用同一block簽名的block的時候,這是一般狀況下最好的方法。 ui
typedef float (^MyBlockType)(float, float); MyBlockType myFirstBlock = // ... ; MyBlockType mySecondBlock = // ... ;
You use the ^
operator to indicate the beginning of a block literal expression. It may be followed by an argument list contained within ()
. The body of the block is contained within {}
. The following example defines a simple block and assigns it to a previously declared variable (oneFrom
)—here the block is followed by the normal ;
that ends a C statement.spa
你使用^操做指示一個block表達的開始。也許還會有一個()包裹的參數列表。block的主體包含在{}中。下面的例子定義了一個簡單的block分配給一個已經存在的變量(oneFrom)——這裏的block是正常的,以C語言作結。.net
float (^oneFrom)(float); oneFrom = ^(float aFloat) { float result = aFloat - 1.0; return result; };
If you don’t explicitly declare the return value of a block expression, it can be automatically inferred from the contents of the block. If the return type is inferred and the parameter list is void
, then you can omit the (void)
parameter list as well. If or when multiple return statements are present, they must exactly match (using casting if necessary).
若是你沒有明確的聲明block表達式的返回值,系統能夠根據block的內容推斷。若是返回類型推斷好,且參數列表爲空,而後你也能夠忽略參數列表。若是須要不少返回值,他們須要寄去匹配(若是必要能夠進行類型轉換)。
At a file level, you can use a block as a global literal:
在文件層面,你能夠把block做爲全局變量。
#import <stdio.h> int GlobalInt = 0; int (^getGlobalInt)(void) = ^{ return GlobalInt; };
本文原創,轉載請註明出處:http://blog.csdn.net/zhenggaoxing/article/details/44308855