O'Reilly logo

Advanced Mac OS X Programming: The Big Nerd Ranch Guide by Mark Dalrymple

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required