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)
    CG_AVAILABLE_STARTING(__MAC_10_4, __IPHONE_2_0);

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:

http://lists.apple.com/archives/quartz-dev/2009/Feb/msg00075.html http://lists.freedesktop.org/archives/cairo/2008-May/014051.html

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.