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

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

When To Copy

So when do you need to copy a block? Make a copy whenever a block will outlive the scope it is defined in. In particular, these snippets are broken:

if (rand() % 1 == 0) {
    blockPtr = ^{ NSLog (@"You are a winner!"); };
} else {
    blockPtr = ^{ NSLog (@"Please try again!"); };
}

The braces for the branches of the if statement introduce a new scope, so the blocks are invalid afterwards.

blockPtr = ^{ NSLog (@"Help me"); };
return blockPtr;

Like returning the address of a local variable, returning a block that is still on the stack will cause problems later on, especially if you capture any local variables whose storage vanishes when the function ends.

BoringBlock blocks[10];
for (int i = 0; i < 10; i++) {
    blocks[i] = ^{
        NSLog (@"captured %d", i);
    };
}

Similar to the if branches, the body of the for loop is a different scope, so the blocks are invalid once the loop ends.

  • + Share This
  • 🔖 Save To Your Account