O'Reilly logo

Advanced Mac OS X Programming: The Big Nerd Ranch Guide by Mark Dalrymple

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

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

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