我对内存管理有一个奇怪的问题让我发疯。我需要异步预加载图像。我有一个代码
- (void)preloadFinishAnimation
{
self.animationImages = [NSMutableArray new];
__weak LearningViewController *weakSelf = self;
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
for (int i = 0; i < NUMBER_OF_ANIMATION_FRAMES; i++) {
UIImage *problemImage = [UIImage imageNamed:[NSString stringWithFormat:@"success-%d", i]];
[weakSelf.animationImages addObject:[weakSelf renderedImageFromImage:image]];
problemImage = nil;
}
});
}
- (UIImage *)renderedImageFromImage:(UIImage *)image
{
UIGraphicsBeginImageContextWithOptions(image.size, NO, 0.0);
CGRect rect = CGRectMake(0, 0, image.size.width, image.size.height);
[image drawInRect:rect];
UIImage *renderedImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return renderedImage;
}
我用Instruments检查过,我知道problemImage不会释放内存。以下是problemImages之一的retain / release命令。
希望有人知道问题出在哪里!
答案 0 :(得分:3)
您必须使用imageWithContentsOfFile:
或initWithContentsOfFile:
代替imageNamed:
,因为imageNamed:
将始终缓存图像,直到系统请求更多内存并清除缓存的图像。
答案 1 :(得分:2)
UIImage imageNamed:缓存图像并按照自己的计划释放内存。 使用“imageWithContentsOfFile”:
[UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:fileName ofType:nil]]