CGImageCreateCopy makes shallow copies

Posted by Brian on November 13, 2010

Both CGImageCreateCopy and CGImageCreateCopyWithColorSpace appear to create a copy of the specified bitmap image. At least that is what the CGImage Reference documentation seems to indicate. However, a look at the CGImage.h header file tells a different story:

/* Return a copy of 'image'. Only the image structure itself is copied; the
   underlying data is not. */
CG_EXTERN CGImageRef CGImageCreateCopy(CGImageRef image)

I discovered this when I was attempting to reuse the buffer that held the bitmap data after making a copy with CGImageCreateCopyWithColorSpace. The “copied” image kept changing to match the most recently loaded bitmap. It appears that others have also discovered this feature:

In my particular case, I found that reusing the buffer did not give much of a performance improvement, so I removed the code that used CGImageCreateCopyWithColorSpace.