When To Copy

So when do you need to copy a block? Make a copy whenever a block will outlive the scope it is defined in. In particular, these snippets are broken:

i​f​ ​(​r​a​n​d​(​)​ ​%​ ​1​ ​=​=​ ​0​)​ ​{​
 ​ ​ ​ ​b​l​o​c​k​P​t​r​ ​=​ ​^​{​ ​N​S​L​o​g​ ​(​@​"​Y​o​u​ ​a​r​e​ ​a​ ​w​i​n​n​e​r​!​"​)​;​ ​}​;​
}​ ​e​l​s​e​ ​{​
 ​ ​ ​ ​b​l​o​c​k​P​t​r​ ​=​ ​^​{​ ​N​S​L​o​g​ ​(​@​"​P​l​e​a​s​e​ ​t​r​y​ ​a​g​a​i​n​!​"​)​;​ ​}​;​
}​

The braces for the branches of the if statement introduce a new scope, so the blocks are invalid afterwards.

b​l​o​c​k​P​t​r​ ​=​ ​^​{​ ​N​S​L​o​g​ ​(​@​"​H​e​l​p​ ​m​e​"​)​;​ ​}​;​
r​e​t​u​r​n​ ​b​l​o​c​k​P​t​r​;​

Like returning the address of a local variable, returning a block that is still on the stack will cause problems ...

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.