I have a custom class Frame
that gets image data from multiple sources. The class can generate an UIImage
. The problem is when a generated UIImage
is drawn on the screen, it crashes with EXC_BAD_ACCESS
.
Callstack is empty, it ends at start->main->UIApplicationMain.
I think it has something to do with CGImageCreate
and that the pointer isn't retained somehow. But I have a hard time figuring out why. The XCode debugger shows the UIImage
exists right before it's added as a subview through UIImageView
, but after it just crashes. I've also tried to draw it directly to a custom UIView
with drawRect
, but it crashes with EXC_BAD_ACCESS
at drawRect
.
Any thoughts would be greatly appreciated!
Here's the code:
UIImage *image = [UIImage imageNamed:@"test.png"];
// To NSData
CGImageRef imageRef = image.CGImage;
CFDataRef dataRef = CGDataProviderCopyData(CGImageGetDataProvider(imageRef));
const unsigned char *pixels = CFDataGetBytePtr(dataRef);
const signed long length = CFDataGetLength(dataRef);
NSData *data = [NSData dataWithBytes:pixels length:length];
CGFloat width = CGImageGetWidth(imageRef);
CGFloat height = CGImageGetHeight(imageRef);
CGBitmapInfo bitmapInfo = CGImageGetBitmapInfo(imageRef);
// NSData to UIImage
CGColorSpaceRef colorSpaceRef = CGColorSpaceCreateDeviceRGB();
CGDataProviderRef dataProviderRef =
CGDataProviderCreateWithData(NULL, data.bytes, data.length, NULL);
CGImageRef imageRef2 =
CGImageCreate(width, height, 8, 32, 4 * width, colorSpaceRef, bitmapInfo,
dataProviderRef, NULL, NO, kCGRenderingIntentDefault);
UIImage *image2 = [UIImage imageWithCGImage:imageRef2];
CGColorSpaceRelease(colorSpaceRef);
CGDataProviderRelease(dataProviderRef);
CGImageRelease(imageRef);
//Show UIImage
UIImageView *imageView = [[UIImageView alloc] initWithFrame:self.view.frame];
imageView.image = image2;
//Breakpoint here shows that `image2` is equal to `image`
[self.view addSubview:imageView];
//EXC_BAD_ACCESS