我的iPhone应用程序从服务器下载图像文件,将其存储到NSTemporaryDirectory()中,然后异步加载UI中的图像。代码流是这样的:
问题是,我使用UIGraphicsGetImageFromCurrentImageContext来缩放图像。看起来图像上下文使用的内存未被清理。随着更多文件的下载,应用内存不断增加。
以下一些代码:
缩放图片的代码:
-(UIImage*)scaleToSize:(CGSize)size image:(UIImage *)imageref
{
UIGraphicsBeginImageContext(size);
[imageref drawInRect:CGRectMake(0, 0, size.width, size.height)];
UIImage* scaledImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return scaledImage;
}
从临时目录加载图片:
-(void)loadImageFromFile: (NSString *) path
{
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
UIImage * imm = [[[UIImage alloc] initWithContentsOfFile:path] autorelease];
[self performSelectorOnMainThread:@selector(insertImage:) withObject:imm waitUntilDone:YES];
[pool release];
}
添加图片到视图(代码子集):
self.imageContainer = [[UIImageView alloc] initWithFrame:CGRectMake(0,80,320,250)];
[self addSubview:self.imageContainer];
self.imageContainer.image = [self scaleToSize:CGSizeMake(320.0f, 250.0f) image:imm];
[imageContainer release];
我在这里缺少什么?
答案 0 :(得分:0)
避免UIGraphicsGetImageFromCurrentImageContext
泄露的一种方法是不要通过调整容器大小来调用它,而不是直接调整图像大小:
self.imageContainer.contentMode = UIViewContentModeScaleAspectFit;
self.imageContainer.frame = CGRectMake(self.imageContainer.frame.origin.x, self.imageContainer.frame.origin.y, 320.0f, 250.0f);