The ownership in UIImage
about CGImage
is unclear. It seems like don't copy the CGImage
but it's not guaranteed by documentation. So we have to handle that ourselves.
I used a new subclass of UIImage
to handle this problem. Just retaining passing CGImage
, and releasing it when the dealloc
.
Here is sample.
@interface EonilImage : UIImage
{
@private
CGImageRef sourceImage;
}
- (id)initWithCGImage:(CGImageRef)imageRef scale:(CGFloat)scale orientation:(UIImageOrientation)orientation;
@end
@implementation EonilImage
- (id)initWithCGImage:(CGImageRef)imageRef scale:(CGFloat)scale orientation:(UIImageOrientation)orientation
{
self = [super initWithCGImage:imageRef scale:scale orientation:orientation];
if (self)
{
sourceImage = imageRef;
CGImageRetain(imageRef);
}
return self;
}
- (void)dealloc
{
CGImageRelease(sourceImage);
[super dealloc];
}
@end
Because the CGImage
returned by -[UIImage CGImage]
property is not guaranteed to be same CGImage
passed into init method, the class stores CGImage
separately.