title: Assigning a delegate to a CALayer's sublayer throws EXC_BAD_ACCESS?
body: <p>I'm trying to use a series of CALayers as sublayers to a view that needs a little more fine grained drawing than usual. I've been using <code>CATiledLayer</code> before, and I thought using sublayers would be easier, if not equally finicky. I figured I perform a <code>[self.layer addSublayer:sublayer]</code>, set the delegate of that new sublayer and then I draw all I want in the <code>drawLayer:inContext:</code> method. But to my great surprise, <strong><em>my app crashes on <code>addSubview:</code></em></strong> (without IB) or somewhere higher up the call stack (when using IB).</p>
  
  <h3>According to the docs ...</h3>
  
  <p>The <a href="https://developer.apple.com/library/ios/#documentation/GraphicsImaging/Reference/CALayer_class/Introduction/Introduction.html#//apple_ref/doc/uid/TP40004500-CH1-SW126">CALayer reference</a> seems to dictate exactly what I'm doing, yet it crashes every time:</p>
  
  <blockquote>
    <p><em>In iOS, if the layer is associated with a UIView object, this property must be set to the view that owns the layer.</em></p>
  </blockquote>
  
  <p>But obviously, I'm screwing something up. Thankfully, it's easily reproducible. Can you explain to me how I should be using sublayers with delegate assignments to receive the right <code>drawLayer:inContext:</code> calls without crashing?</p>
  
  <h3>Steps to reproduce</h3>
  
  <p>Put this in the class of a custom view put on screen with Interface Builder (or rewrite the init to be called <code>initWithFrame:</code>):</p>
  
  <pre><code>- (id)initWithCoder:(NSCoder *)aDecoder {
      self = [super initWithCoder:aDecoder];
  
      if (self) {
          CALayer *sublayer = [CALayer layer];
          sublayer.frame = self.layer.bounds;
  
          // Disable or enable this next line to 
          // resolve or trigger an EXC_BAD_ACCESS crash.
          // 
          sublayer.delegate = self;
  
          [self.layer addSublayer:sublayer];
          [self.layer setNeedsDisplay];
      }
  
      return self;
  }
  
  - (void)drawLayer:(CALayer *)layer inContext:(CGContextRef)ctx {
      CGContextSetFillColorWithColor(ctx, [[UIColor greenColor] CGColor]);
      CGContextFillRect(ctx, self.bounds);
  }
  </code></pre>
  
  <p>If you run this code, your app will crash. Mind the <code>sublayer.delegate = self</code> line. If you disable that one, your app will run, but the <code>drawLayer:inContext:</code> method is never called for that sublayer. </p>
  
  <p>What am I doing wrong?</p>