title: NSData over GameKit and EXC_BAD_ACCESS strange problem
body: <p>I'm trying to stream video data over a peer-to-peer connection created with GameKit. I have a method that receives an NSData object and uses it to draw a video stream onto a CALayer:</p>
  
  <pre><code>- (void)recieveVideoFromData:(NSData *)data;
  </code></pre>
  
  <p>Here are the first few lines of that method which convert the NSData to CMSampleBufferRefs and begins processing:</p>
  
  <pre><code>CMSampleBufferRef imgData = (CMSampleBufferRef)data.bytes;
  CVImageBufferRef imageBuffer = CMSampleBufferGetImageBuffer(imgData); 
  CVPixelBufferLockBaseAddress(imageBuffer,0); 
  </code></pre>
  
  <p>Now, when I feed the video stream from the local camera into this method as follows, everything works just fine and the video stream displays on screen:</p>
  
  <pre><code>- (void)captureOutput:(AVCaptureOutput *)captureOutput didOutputSampleBuffer:(CMSampleBufferRef)sampleBuffer fromConnection:(AVCaptureConnection *)connection { 
      NSData *data = [[NSData alloc] initWithBytes:sampleBuffer length:malloc_size(sampleBuffer)];
      [self recieveVideoFromData:data]; 
  }
  </code></pre>
  
  <p>But, when I send a stream of those NSData packets over a peer-to-peer connection and receive them in the following fashion, I get an EXC_BAD_ACCESS error:</p>
  
  <pre><code>- (void)match:(GKMatch *)match didReceiveData:(NSData *)data fromPlayer:(NSString *)playerID {
      [self recieveVideoFromData:data];
  }
  </code></pre>
  
  <p>Using the debugger, I learned that the bad access occurs on this line:</p>
  
  <pre><code>CVPixelBufferLockBaseAddress(imageBuffer,0); 
  </code></pre>
  
  <p>I have no idea why the NSData sent over the network should be any different than the NSData sent from another method on the same device. I have checked that the data received over the network is being received at the same interval and is the same length (336 bytes) as the data produced on the local device. I also checked the retain count of the <strong>data</strong> object is 1 before it is used. It seems that the <strong>imageBuffer</strong> variable is somehow getting lost.</p>
  
  <p>A couple of questions:</p>
  
  <ol>
  <li><p>Is casting <strong>data.bytes</strong> to a <strong>CMSampleBufferRef</strong> the right way to go about unpacking NSData?</p></li>
  <li><p>How do I assert that the data being received is actually a CMSampleBuffer object? I want to protect my code but I'm not sure how to accomplish a class verification for Core Foundation classes.</p></li>
  </ol>
  
  <p>Thanks in advance!</p>