内存管理UIImage ImageNamed

时间:2012-05-22 15:25:15

标签: iphone cocoa-touch memory-management uiimage

我使用

在我的viewcontroller中加载了大量相当大的图像
NSUInteger nimages = 0;

for (; ; nimages++) {

    NSString *nameOfImage_ = @"someName";

    NSString *imageName = [NSString stringWithFormat:@"%@%d.jpg", nameOfImage_, (nimages + 1)];

    image = [UIImage imageNamed:imageName];
    if (image == nil) {
        break;
    }

    UIImageView *imageView = [[UIImageView alloc] initWithImage:image];

    //some other stuff....

    [imageView release];
}

通常的卸载发生在 - (void)viewDidUnload和 - (void)dealloc中 with self.image = nil;和[图像发布];

似乎经过一些“加载”和“卸载”后,缓存仍然增长到了不归路! :)

并且应用程序崩溃......

任何想法???我如何清空缓存?在哪里?

感谢

编辑:

好吧,这就是我做错了。 显然,这段代码修复了整个缓存问题:

image = [[UIImage imageNamed:imageName] autorelease];

以自动释放为关键。

感谢回复......

5 个答案:

答案 0 :(得分:4)

谢谢大家的建议。

解决方案:
使用ARCimageWithContentsOffFile初始化图像。

image = [UIImage imageWithContentsOfFile: [[NSBundle mainBundle] pathForResource:imageName ofType:nil]];

并且imageNamed只对...有好处......对于没有什么大事......

答案 1 :(得分:3)

image = [[UIImage imageNamed:imageName] autorelease];

这是不正确的。为了与内存管理规则保持一致,您不应该释放(或自动释放)映像,因为您没有分配或保留它。 “imageNamed”不包含“alloc”,“new”,“copy”或“retain”。

正如其他一些答案所解释的那样,如果您想要更多地控制他们使用的内存,您应该使用不同的方法加载图像。

答案 2 :(得分:1)

imageNamed是一种实际加载图像的糟糕方式,它永远不会释放加载的图像,除非被强制并永久保存在缓存中。您应该实现自己的,更智能的缓存。简单的NSMutableDictionary提供相同的功能,但具有更大的灵活性。

有关更深入的讨论,请参阅:http://www.alexcurylo.com/blog/2009/01/13/imagenamed-is-evil/

答案 3 :(得分:0)

使用其他方法初始化图像。 imageNamed缓存。

答案 4 :(得分:0)

您可以使用imageWithContentsOfFile而不是使用imageNamed: 或者查看这篇文章

link 0

link 1