Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
779 views
in Technique[技术] by (71.8m points)

iphone - 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;

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.)

If I replace the UIGraphicsBeginImageContext to UIGraphicsEndImageContext with

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)

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 :)?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

I add

background.layer.contents = nil;

after

UIGraphicsEndImageContext();

and the cached memory in the layer is uncached :).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...