Home > Articles > Home & Office Computing > Mac OS X

  • Print
  • + Share This
This chapter is from the book

Blocks in Collections

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

NSMutableArray *blockArray = [NSMutableArray array];
[blockArray addObject: ^{
        NSLog (@"Jen makes great cupcakes!");

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 the implicit retain from -copy.

[array addObject: [[^{
        NSLog (@"Jen makes great cupcakes!");
    } copy] autorelease]];

Yes. It looks weird, but it's necessary.

  • + Share This
  • 🔖 Save To Your Account