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

Variable Capture Redux

Let’s revisit variable capture. Each of the blocks here is the same code, but they are created at different times – each after the value of val has changed.

t​y​p​e​d​e​f​ ​v​o​i​d​ ​(​^​B​o​r​i​n​g​B​l​o​c​k​)​ ​(​v​o​i​d​)​;​

i​n​t​ ​v​a​l​ ​=​ ​2​3​;​
B​o​r​i​n​g​B​l​o​c​k​ ​b​l​o​c​k​1​ ​=​ ​^​{​ ​N​S​L​o​g​ ​(​@​"​%​d​"​,​ ​v​a​l​)​;​ ​}​;​

v​a​l​ ​=​ ​4​2​;​
B​o​r​i​n​g​B​l​o​c​k​ ​b​l​o​c​k​2​ ​=​ ​^​{​ ​N​S​L​o​g​ ​(​@​"​%​d​"​,​ ​v​a​l​)​;​ ​}​;​

v​a​l​ ​=​ ​1​7​;​
B​o​r​i​n​g​B​l​o​c​k​ ​b​l​o​c​k​3​ ​=​ ​^​{​ ​N​S​L​o​g​ ​(​@​"​%​d​"​,​ ​v​a​l​)​;​ ​}​;​

block1 points to a block that has captured val when it had a value of 23. block2 points to a block that has captured val when it had a value of 42, and likewise ...

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