O'Reilly logo

iOS Programming: The Big Nerd Ranch Guide by Joe Conway, Aaron Hillegass

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

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