Blocks as Objects

Interestingly enough, blocks are also objects and can be stored in collections. Blocks start out life on the call stack, making them the only stack-based Objective-C objects. The block’s executable code does not actually live on the stack, but all of the data the block uses, such as local variables and captured variables, lives there.

Because these blocks live on the stack, you need to make a copy of the block into the heap if it is to live beyond the current scope. When you copy a block, any captured variables are copied into the heap as well. Figure 3.1 shows the block data on the stack for this block:

i​n​t​ ​s​t​r​i​d​e​ ​=​ ​1​0​;​ _​_​b​l​o​c​k​ ​i​n​t​ ​s​u​m​m​a​t​i​o​n​ ​=​ ​0​;​ B​o​r​i​n​g​B​l​o​c​k​ ​b​l​o​c​k​P​t​r​ ...

Get Advanced Mac OS X Programming: The Big Nerd Ranch Guide now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.