在循环中释放renderInContext结果

Car*_*ine 8 memory iphone quartz-graphics

我有一个在循环中调用的方法,看起来像这样:

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;
Run Code Online (Sandbox Code Playgroud)

但是,根据Instruments Memory Monitor的说法,内存使用量会不断上升,直到循环结束才会下降.(它崩溃了.)

如果我将UIGraphicsBeginImageContext替换为UIGraphicsEndImageContext

UIImage*image = someotherimage;

然后内存不会出现峰值,但是在循环的每次迭代中都会被分配和减少,正如我所期望的那样,由于自动释放池.(它没有崩溃)

如果我只是注释掉renderInContext行,它可以正常工作.(不会崩溃)

因此看起来好像renderInContext以某种方式保留在图像上 - 我怎样才能让它释放它?或者任何替代建议请:)?

Car*_*ine 15

经过3天的实验,我在一小时内找到了答案(答案,无论如何,我很乐意对此发表评论).

我加

background.layer.contents = nil;
Run Code Online (Sandbox Code Playgroud)

UIGraphicsEndImageContext();
Run Code Online (Sandbox Code Playgroud)

并且图层中的缓存内存未缓存:).