Cover by Joe Conway, Aaron Hillegass

Safari, the world’s most comprehensive technology and business learning platform.

Find the exact information you need to solve a problem on the fly, or go deeper to master the technologies and skills you need to succeed

Start Free Trial

No credit card required

O'Reilly logo

Variable Capturing

There is one special characteristic of blocks that makes them very useful: they capture variables.

A block, like a function, can use the arguments passed to it and can declare local variables. Modify the block in BNRAppDelegate.m’s application:​didFinishLaunchingWithOptions: so that it declares and uses a local variable.

[​e​x​e​c​u​t​o​r​ ​s​e​t​E​q​u​a​t​i​o​n​:​^​i​n​t​(​i​n​t​ ​x​,​ ​i​n​t​ ​y​)​ ​{​
 ​ ​ ​ ​i​n​t​ ​s​u​m​ ​=​ ​x​ ​+​ ​y​;​
 ​ ​ ​ ​r​e​t​u​r​n​ ​x​ ​+​ ​y​;​
 ​ ​ ​ ​r​e​t​u​r​n​ ​s​u​m​;​
}​]​;​

The variable sum is local to the block, so sum can be used inside this block. Both x and y are arguments of the block, so they, too, can be used inside this block.

A block can also use any variables that are visible ...

Find the exact information you need to solve a problem on the fly, or go deeper to master the technologies and skills you need to succeed

Start Free Trial

No credit card required