调用CGImage时EXC_BAD_ACCESS

时间:2012-09-10 23:55:21

标签: iphone ios

我有以下代码:

UIImage *img = [UIImage imageNamed:@"BRBlueCircleMask"];
CGImageRef activeCirleMaskImage = img.CGImage;
activeCirleMaskLayer = [CALayer layer];
activeCirleMaskLayer.frame = CGRectMake(0, 0, 50, 50);
activeCirleMaskLayer.contents = CFBridgingRelease(activeCirleMaskImage);

EXC_BAD_ACCESS在70%的时间内在第二行发生(即有时它可以正常工作)。 有什么问题?

2 个答案:

答案 0 :(得分:2)

此代码段中的问题并不明显,即使图像无法加载(图像引用最终将为NULL),该代码片段仍然可以正常工作。

您可能在其他地方出现了内存管理问题,并且/或者调试器对崩溃的位置感到困惑。

答案 1 :(得分:2)

按如下方式更改您的代码(另外,我假设您使用的是ARC)。首先,我将为现有代码添加注释,然后向您展示如何解决问题

// While this is a strong reference, ARC can release it after 'img.CGImage' (I have an accepted bug on this)
UIImage *img = [UIImage imageNamed:@"BRBlueCircleMask"];
// ARC should cause 
CGImageRef activeCirleMaskImage = img.CGImage;
 // you do not own the image, and a current ARC bug causes this object SOMETIMES to get released immediately after the assignment!!!
activeCirleMaskLayer = [CALayer layer];
activeCirleMaskLayer.frame = CGRectMake(0, 0, 50, 50);
activeCirleMaskLayer.contents = CFBridgingRelease(activeCirleMaskImage); // You are releasing an object here you don't own, which is the root cause of your problem

按如下方式更改您的代码

UIImage *img = [UIImage imageNamed:@"BRBlueCircleMask"];
// want to get the CGImage copied ASAP
CGImageRef activeCirleMaskImage = CGImageCreateCopy(img.CGImage); // now you own a copy
activeCirleMaskLayer = [CALayer layer];
activeCirleMaskLayer.frame = CGRectMake(0, 0, 50, 50);
activeCirleMaskLayer.contents = CFBridgingRelease(activeCirleMaskImage); // OK now, its your copy
PS:如果有人不相信CGImage的积极发布不真实,我会很高兴发布我的错误报告(以及展示行动中问题的演示项目)

编辑:苹果已经解决了这个问题,我相信它是在iOS6中。他们现在跟踪内部指针的使用并阻止释放内存,直到指针超出范围。修复是在SDK和头文件被定义,所以你需要链接到iOS6或7 - 可能需要一个不太确定的部署目标。