renderInContext抛出崩溃

时间:2013-04-12 19:17:07

标签: ios objective-c core-graphics quartz-graphics

我正在从webview渲染图像。所以renderIncontext方法在for循环中调用超过50次。经过20或30次我的应用程序因为更多的内存消耗而崩溃。

我使用了这段代码:

UIGraphicsBeginImageContext(CGSizeMake([w floatValue], [h floatValue]));
CGContextRef ctx = UIGraphicsGetCurrentContext();
[[UIColor blackColor] set];
CGContextFillRect(ctx, webview.frame);
[self.webview.layer renderInContext:ctx];
image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();

经过20次坠毁。我需要它的解决方案。

为什么会这样?有人知道吗?

1 个答案:

答案 0 :(得分:2)

听起来你在紧密的循环中创建了大量的位图图像。你需要保存你需要的图像(如果你需要它们,可能在磁盘上而不是在内存中),并允许内存中的图像自动释放。将循环体包裹在@autorelease块中,如:

for (whatever) {
    @autorelease {
        // Work that makes big autoreleased objects.
    }
}

这样你的内存消耗就不会在你的循环内失控。同样,如果你让所有这些UIImage对象持续存在,你仍然会分配大量的内存。将生成的图像保存到磁盘上的临时目录(或其他方便的位置),并根据需要单独获取它们。