11

If I declare a block like this ^{ DoSomething; } and put it in an instance variable, do I need to Block_copy() if I'm going to keep it around?

brian
  • 3,344
  • 2
  • 26
  • 35

1 Answers1

11

Yes, you need to copy. Not because they are autoreleased, but because they start on the stack. Note that blocks also behave like regular Objective-C objects, so that you can copy them using the regular copy message:

void storeBlockForLater: (dispatch_block_t) block
{
    [someArray addObject:[[block copy] autorelease]];
}

Or, if you have a block property:

@property(copy) dispatch_block_t block;

Retaining does not help here.

zoul
  • 102,279
  • 44
  • 260
  • 354
  • 2
    Thanks, I also found this great article on the subject: http://cocoawithlove.com/2009/10/how-blocks-are-implemented-and.html – brian Jan 12 '11 at 11:51
  • 1
    Yup; and if you use `copy`, use `release`. If you you use `Block_copy()`, use `Block_release()`. Don't mix 'em. – bbum Jan 12 '11 at 17:17
  • @bbum Is it safe to use `Block_copy()` and `autorelease`? Should you only use `autorelease` with `copy`? – Nick Forge Apr 05 '11 at 03:53
  • 1
    @openfrog: You still need to copy the block, but that’s all. You don’t have to – and can’t – release nor autorelease it. – zoul Dec 18 '12 at 15:56