Iphone 在循环中释放RenderContext结果
我有一个在循环中调用的方法,看起来像这样:Iphone 在循环中释放RenderContext结果,iphone,memory,quartz-graphics,Iphone,Memory,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 viewArr
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,内存使用率不断上升,直到循环结束时才会下降。(它崩溃了。)
如果将UIGraphicsBeginImageContext替换为UIGraphicsSendImageContext
UIImage*image=someotherimage
然后,由于自动释放池,内存不会尖峰,而是在循环的每次迭代中分配和减少,正如我预期的那样。(它不会崩溃)
如果我只是注释掉renderInContext行,它就可以正常工作了。(不会崩溃)
所以看起来RenderContext似乎以某种方式抓住了图像-我如何才能让它释放它?或者任何其他建议:)?当然,经过3天的实验,我在一小时内找到了答案(无论如何,答案是肯定的,我很乐意就此发表评论) 我补充说 之后
层中的缓存内存未缓存:)。我没有使用UIImageView,因此设置
layer.contents=nil
对我不起作用。然而,我发现了一个不同的解决方案,虽然不理想,但确实有效。在主队列空闲之前,renderInContext
分配的内存似乎不会被释放。因此,我做了以下工作:
dispatch_queue_t queue = dispatch_queue_create("com.example.imageprocessing", DISPATCH_QUEUE_SERIAL);
for (int k = 0; k < images.count; ++k) {
dispatch_async(queue, ^{
dispatch_sync(dispatch_get_main_queue(), ^{
@autoreleasepool {
...
UIGraphicsBeginImageContext(self.view.bounds.size);
[view.layer renderInContext:UIGraphicsGetCurrentContext()];
image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
...
}
}
}
}
dispatch\u queue\u t queue=dispatch\u queue\u create(“com.example.imageprocessing”,dispatch\u queue\u SERIAL);
对于(int k=0;k
这解决了我的内存问题。我没有处理很多图像,所以我不知道性能会受到什么影响
UIGraphicsEndImageContext();
dispatch_queue_t queue = dispatch_queue_create("com.example.imageprocessing", DISPATCH_QUEUE_SERIAL);
for (int k = 0; k < images.count; ++k) {
dispatch_async(queue, ^{
dispatch_sync(dispatch_get_main_queue(), ^{
@autoreleasepool {
...
UIGraphicsBeginImageContext(self.view.bounds.size);
[view.layer renderInContext:UIGraphicsGetCurrentContext()];
image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
...
}
}
}
}