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.
typedef void (^BoringBlock) (void); int val = 23; BoringBlock block1 = ^{ NSLog (@"%d", val); }; val = 42; BoringBlock block2 = ^{ NSLog (@"%d", val); }; val = 17; BoringBlock block3 = ^{ NSLog (@"%d", val); };
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 block3's val captured the value of 17. Invoking the blocks prints out the captured values of val:
block1 (); block2 (); block3 ();
prints
23 42 17
Now, make a single change to the code, making val a __block-scoped variable:
typedef void (^BoringBlock) (void); __block int val = 23; BoringBlock block1 = ^{ NSLog (@"%d", val); }; val = 42; BoringBlock block2 = ^{ NSLog (@"%d", val); }; val = 17; BoringBlock block3 = ^{ NSLog (@"%d", val); };
Invoking the blocks as above will print:
17 17 17
The same value is printed because all blocks are sharing the same storage for val rather than making copies.