Block objects provide a way for you to create an ad hoc function body as an expression in C, and C-derived languages such as Objective-C and C++. In other languages and environments, a block object is sometimes also called a “closure”. Here, they are typically referred to colloquially as “blocks”, unless there is scope for confusion with the standard C term for a block of code.
block對象給你提供了創建C語言和C語言拓展語言,比如objective-C和C++中的 ad hoc函數的可能。在其他語言環境中,block對象有時也被稱作“closure”,這裡呢,通常用大白話稱為:“block”,除非作用域中有復雜的標准C block代碼。
A block is an anonymous inline collection of code that:
Has a typed argument list just like a function
Has an inferred or declared return type
Can capture state from the lexical scope within which it is defined
Can optionally modify the state of the lexical scope
Can share the potential for modification with other blocks defined within the same lexical scope
Can continue to share and modify state defined within the lexical scope (the stack frame) after the lexical scope (the stack frame) has been destroyed
You can copy a block and even pass it to other threads for deferred execution (or, within its own thread, to a runloop). The compiler and runtime arrange that all variables referenced from the block are preserved for the life of all copies of the block. Although blocks are available to pure C and C++, a block is also always an Objective-C object.
一個block是一個匿名內聯代碼集:
像函數一樣有一個類型參數列表。有一種推斷或聲明的返回值類型可以在它定義的詞法范圍內捕獲狀態可以隨意的在詞法作用域裡面修改狀態可以和相同作用域的block分享修改可以在詞法作用域(棧)被銷毀後繼續分享和修改詞法作用域中的狀態。 你可以復制一個block甚至將它延期到其他線程執行(或者在自己的進程中加入一個循環隊列)。編譯器和運行時安排所有block的相關變量保存在所有block的拷貝的生命周期中。盡管block可以在純C和C++中使用,在objective-C中也經常使用block對象。
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:
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.
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經常被用於作為一個可能同時執行的封裝單元,或者集合中的項,或者當操作結束時候的回調。 blocks 因為如下兩個原因成為回調函數的一個有效替代者: 他們允許你在調用點(函數內容已經結束啦)之後寫代碼。因此呢block常常作為框架函數的參數出現。他們允許你訪問本地變量。相比於回調函數要求操作的所有上下文信息,block只需要直接訪問本地變量就行了。