title: Objective-C Blocks with closure that references the host object
body: <p>I've been playing with blocks and encountered a weird behavior.
  This is the interface/implementation, which just holds a block with the ability to execute it:</p>
  
  <pre><code>@interface TestClass : NSObject {
  #if NS_BLOCKS_AVAILABLE
      void (^blk)(void);
  #endif
  }
  - (id)initWithBlock:(void (^)(void))block;
  - (void)exec;
  @end
  
  @implementation TestClass
  #if NS_BLOCKS_AVAILABLE
  - (id)initWithBlock:(void (^)(void))block {
      if ((self = [super init])) {
          blk = Block_copy(block);
      }
      return self;
  }
  - (void)exec {
      if (blk) blk();
  }
  - (void)dealloc {
      Block_release(blk);
      [super dealloc];
  }
  #endif
  @end
  </code></pre>
  
  <p>While a regular instantiation and passing a regular block works:</p>
  
  <pre><code>TestClass *test = [[TestClass alloc] initWithBlock:^{
      NSLog(@"TestClass");
  }];
  [test exec];
  [test release];
  </code></pre>
  
  <p>Using a block with reference to the object which is being created doesn't:</p>
  
  <pre><code>TestClass *test1 = [[TestClass alloc] initWithBlock:^{
      NSLog(@"TestClass %@", test1);
  }];
  [test1 exec];
  [test1 release];
  </code></pre>
  
  <p>Error is EXC_BAD_ACCESS, stack trace on Block_copy(block);
  Debugger on: 0x000023b2  &lt;+0050>  add    $0x18,%esp</p>
  
  <p>I kept playing around, and moved the allocation code above the initialization, it worked:</p>
  
  <pre><code>TestClass *test2 = [TestClass alloc];
  test2 = [test2 initWithBlock:^{
      NSLog(@"TestClass %@", test2);
  }];
  [test2 exec];
  [test2 release];
  </code></pre>
  
  <p>And combining both snippets works too:</p>
  
  <pre><code>TestClass *test1 = [[TestClass alloc] initWithBlock:^{
      NSLog(@"TestClass %@", test1);
  }];
  [test1 exec];
  [test1 release];
  
  TestClass *test2 = [TestClass alloc];
  test2 = [test2 initWithBlock:^{
      NSLog(@"TestClass %@", test2);
  }];
  [test2 exec];
  [test2 release];
  </code></pre>
  
  <p>What's going on here?</p>