UIImageView泄漏/自动释放

时间:2012-05-28 21:32:44

标签: iphone xcode

我正在运行一个相当内存密集的循环来生成图像,并且在内存泄漏/自动释放保留内存分配的时间过长了。

任何人都可以详细解释下面正在举行和自动发布的内容吗?我通过Allocations工具运行它,它的大小增加,直到循环结束并释放所有自动释放对象(据我所知,从3天的试验和错误)。这对于较少的循环是可以的,但是当我超过200时,它最终会在自动释放之前崩溃。通过注释掉以下代码,此增加将停止,仪器图形将与设定的内存量保持水平:

   for (int l=0;1 < 300; 1++) {
      UIImage * Img = [[UIImage alloc] initWithContentsOfFile:Path]; //Path is a NSString pointing to bundlePath and a sample image
      UIImageView *ImgCont = [[UIImageView alloc] initWithImage:Img];

      //here I usually add the view to a UIView but it is not required to see the problem
      ImgCont.frame = CGRectMake(x, y, w, h);

      [ImgCont release];
      [Img release];
   }

我尝试用NSAutoreleasePool包装这个没有成功 - 任何想法我做错了什么?

谢谢,

2 个答案:

答案 0 :(得分:2)

当您将imageView添加到视图时,它会被该视图保留,因此即使您释放Img和ImgCont,它们仍然存在,并且您将留下300个对象。

另外,我并不完全确定这一点,但是如果你反复使用相同的图像,你应该使用[UIImage imageNamed:NAME],因为它重用了图像,这是我不能说的[ UIImage initWithContentsOfFile:PATH]; (如果操作系统没有优化这种情况,那么现在你在内存中有相同的图像300次。)

答案 1 :(得分:1)

您明确创建的对象都没有被自动释放,因此它必须是您拥有的UIKit调用内的东西。尽管在减少自动释放的数量方面,你可以做很多事情。但你可以做的就是搞乱自动释放池。

你说你已经尝试了NSAutoreleasePool,但你是否尝试将循环的每次迭代包装在一个池中,如下所示:

for (int l=0;1 < 300; 1++) {
    @autoreleasepool {
        UIImage * Img = [[UIImage alloc] initWithContentsOfFile:Path]; //Path is a NSString pointing to bundlePath and a sample image
        UIImageView *ImgCont = [[UIImageView alloc] initWithImage:Img];

        //here I usually add the view to a UIView but it is not required to see the problem
        ImgCont.frame = CGRectMake(x, y, w, h);

        [ImgCont release];
        [Img release];
    }

}

虽然你应该考虑不要那样做,因为它可能有点过分。但我建议你尝试一下,如果你还有问题,那就不是这个循环。

相关问题