title: Releasing an IOSurface
body: <p>This question is an extension to: <br/>
  Link-1: <a href="https://stackoverflow.com/questions/13872728/creating-an-image-out-of-the-ios-surface-and-saving-it">Creating an image out of the ios surface and saving it</a> <br/>Link-2: <a href="https://stackoverflow.com/questions/13833816/taking-screenshots-from-ios-app-emulating-display-recorder-query-on-the-inter">Taking Screenshots from iOS app - emulating Display recorder (query on the internals)</a> <br/></p>
  
  <p>(Refer Link-1) I have the code for taking screenshots in the background working. But as stated, it requires a sleep of 2 sec to work uninterruptedly, otherwise the OS suspends the app. I figured out the reason could be that I am not explicitly releasing the IOSurface I create. <br/>
  Reason - Using the link <a href="http://pastie.org/pastes/3734430" rel="nofollow noreferrer">http://pastie.org/pastes/3734430</a> given by Victor Ronin, the capture works fine even without the sleep.
  I tried releasing the destSurf (destination surface that I have created) using CFRelease after I write the image each time, but that doesn't work.</p>
  
  <p>Any help on when, how and whether or not to release a created IOSurface, will be really useful. Thanks. <br/><br/>
  <strong>Update</strong> <br/>
  So, this is what exactly happens. (Referring Link-1) <br/></p>
  
  <pre><code>IOSurfaceRef destSurf = IOSurfaceCreate(dict);
  IOSurfaceAcceleratorRef outAcc;
  IOSurfaceAcceleratorCreate(NULL, 0, &amp;outAcc);
  
  CFDictionaryRef ed = (__bridge CFDictionaryRef)[NSDictionary dictionaryWithObjectsAndKeys: nil];
  IOSurfaceAcceleratorTransferSurface(outAcc, screenSurface, destSurf, ed, NULL);
  
  IOSurfaceUnlock(screenSurface, kIOSurfaceLockReadOnly, &amp;aseed);
  
  CGDataProviderRef provider = CGDataProviderCreateWithData(NULL, IOSurfaceGetBaseAddress(destSurf), (width*height*4), NULL);
  CGImageRef cgImage=CGImageCreate(width, height, 8, 8*4, IOSurfaceGetBytesPerRow(destSurf), CGColorSpaceCreateDeviceRGB(), kCGImageAlphaNoneSkipFirst | kCGBitmapByteOrder32Little, provider, NULL, YES, kCGRenderingIntentDefault);
  UIImage *image = [UIImage imageWithCGImage: cgImage];
  CGImageRelease(cgImage);
  UIImageWriteToSavedPhotosAlbum(image, self, nil, nil);
  CFRelease(destSurf);
  </code></pre>
  
  <ol>
  <li>The call to CFRelease takes place and app crashes. There are no images saved. However, if you put in a sleep of 1-2 sec prior to the release, it works fine. 
  <li>If you skip the call to UIImageWriteToSavePhotosAlbum(), everything works fine and capture goes without interruption. <br/>
  I am still not clear on what exactly is the problem and how to solve it. Any help is highly appreciated.</li>
  </ol>