【发布时间】:2019-06-08 03:30:59
【问题描述】:
我在我的应用中启用了 ARC,并注意到如果我创建大量图像,我的应用会崩溃。作为调查的一部分,我创建了一个小项目来重现该问题,该问题可以在here 找到。示例项目代码的内容如下:
int width = 10;
int height = 10;
uint8_t data[100];
while (true)
{
CGColorSpaceRef colorspace = CGColorSpaceCreateDeviceGray();
CGContextRef context = CGBitmapContextCreate(data, width, height, 8, width, colorspace, kCGBitmapByteOrderDefault | kCGImageAlphaNone);
CGImageRef cgimage = CGBitmapContextCreateImage(context);
// Remove this line and memory is stable, keep it and you lose 15-20 MB per second. Why?
UIImage* uiimage = [UIImage imageWithCGImage:cgimage];
CGImageRelease(cgimage);
CGContextRelease(context);
CGColorSpaceRelease(colorspace);
}
运行此代码时,Xcode 中的侧边栏将显示应用程序的总内存以每秒 15-20 MB 左右的速度增加。如果您注释掉创建UIImage 的行,泄漏就会消失。
Stack Overflow 上有很多关于在通过imageWithCGImage 创建 UIImage 后是否应该发布CGImage 的问题,看起来并没有真正的共识。但是,如果我不调用CGImageRelease(cgimage),那么内存使用量每秒会增加超过 100 MB,所以我确信手动释放图像是正确的做法。
由于我启用了 ARC,我尝试在释放所有内容后将 uiimage 设置为 nil,但没有成功。不存储对imageWithCGImage: 的调用的返回值也不能防止泄漏。
关于如何使用 Core Graphics,我是否缺少一些基本知识?
【问题讨论】:
标签: memory-leaks core-graphics