在循环中释放renderInContext结果 [英] Releasing renderInContext result within a loop
问题描述
我有一个在循环中调用的方法,看起来像这样:
I have a method which is called in a loop, that looks something like this:
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
UIImageView *background = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, PAGE_WIDTH, PAGE_HEIGHT)];
background.image = backgroundImg;
for (UIView *view in viewArray)
{
[background addSubview:view];
}
UIGraphicsBeginImageContext(background.frame.size);
[background.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
for (UIView *view in background.subviews)
[view removeFromSuperview];
background.image = nil;
[background release];
[image retain];
[pool drain];
[image autorelease];
return image;
然而,根据Instruments Memory Monitor的说法,内存使用量会不断上升,直到循环结束。 (它崩溃了。)
However, according to Instruments Memory Monitor, the memory usage goes up and up, and never comes down until the end of the loop. (It crashes.)
如果我将UIGraphicsBeginImageContext替换为UIGraphicsEndImageContext与
If I replace the UIGraphicsBeginImageContext to UIGraphicsEndImageContext with
UIImage * image = someotherimage;
UIImage *image = someotherimage;
然后内存不会出现峰值,但是在循环的每次迭代中都会被分配并减少,正如我所料,由于自动释放池。 (它没有崩溃)
then the memory does not spike, but is allocated and reduces on every iteration of the loop, as I would expect, due to the Autorelease pool. (It doesn't crash)
如果我只注释掉renderInContext行,它就可以了。 (不会崩溃)
And if I just comment out the renderInContext line it works fine. (Doesn't crash)
所以看起来渲染的图像似乎是以某种方式保留在图像上 - 如何让它释放它?或者任何其他建议请:)?
So it looks as if renderInContext is holding onto the image somehow - how can I get it to release it? Or any alternative suggestions please :)?
推荐答案
自然经过3天的实验,我找到了答案(答案,无论如何,我会很高兴在一小时内发表评论。
Naturally after 3 days of experimenting, I find the answer (an answer, anyway, and I would be glad of comments on this) within the hour.
我添加
background.layer.contents = nil;
UIGraphicsEndImageContext();
并且图层中的缓存内存未缓存:)。
and the cached memory in the layer is uncached :).
这篇关于在循环中释放renderInContext结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!