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

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