Blocks in Collections

You need to copy a block before you add it to a Cocoa collection class. Consider this erroneous code:

N​S​M​u​t​a​b​l​e​A​r​r​a​y​ ​*​b​l​o​c​k​A​r​r​a​y​ ​=​ ​[​N​S​M​u​t​a​b​l​e​A​r​r​a​y​ ​a​r​r​a​y​]​;​
[​b​l​o​c​k​A​r​r​a​y​ ​a​d​d​O​b​j​e​c​t​:​ ​^​{​
 ​ ​ ​ ​ ​ ​ ​ ​N​S​L​o​g​ ​(​@​"​J​e​n​ ​m​a​k​e​s​ ​g​r​e​a​t​ ​c​u​p​c​a​k​e​s​!​"​)​;​
 ​ ​ ​ ​}​]​;​

The stack-based block object has its address passed to -addObject:. -addObject: retains the passed-in object. Because the block is still on the stack, -retain is a no-op. The block becomes invalid when the calling function exits, waiting to blow up when you use it in the future. You fix this by copying it before putting it into the collection. Do not forget to offset ...

Get Advanced Mac OS X 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.