什麼是區塊(Blocks)?
Blocks 很像函式(functions), 但以 inline寫成並且包含在其他函式中。它也被稱為(closure), 因他會存在於最近的變數空間. (它也被叫做lambdas).
在 Cocoa (Mac 圖形介面函式庫), 區塊常用在
- 回撥函式(callbacks): 如LOG處理
- 延後執行(delayed execution): 如非同步的檔案寫入的完成通知
註:Apple介紹Block主因極可能是用區塊來做更好的平行處理 (concurrency),
可參考Grand Central Dispatch (GCD))
下列是一個改寫自原文範例
/***********************************************/
// In mathematics, an arithmetic progression (AP) or arithmetic sequence is a sequence of
// numbers such that the difference of any two successive members of the sequence is a constant. For instance, the sequence 3, 5, 7, 9, 11, 13,
// … is an arithmetic progression with common difference 2.
// Example for blocks with (AP)
#include
#include
// define block
typedef int (^IntBlock)();
IntBlock mathAP(int firstTerm, int difference) {
__block int computeTerm = firstTerm;
return Block_copy( ^ {
computeTerm += difference;
return computeTerm;
});
}
int mathAPloop(int n, IntBlock blockAP)
{
int m = n;
while (n-- > 0) {
printf("a%d: %d\n", m - n, blockAP());
}
return 0;
}
int main() {
IntBlock blockAP = mathAP(1, 3);
mathAPloop(10, blockAP);
Block_release(blockAP);
return 0;
}
/***********************************************/
結果如下:
a1: 4
a2: 7
a3: 10
a4: 13
a5: 16
a6: 19
a7: 22
a8: 25
a9: 28
a10: 31
更新07-25
此篇範例,請到GitHub程式碼下載。