2010-06-02 41 views
0

仪器的泄漏告诉我,这UIImage的泄漏:为什么这个泄漏的内存? UIImage的`的cellForRowAtIndexPath:`

UIImage *image = [[UIImage alloc] initWithContentsOfFile:[imagesPath stringByAppendingPathComponent:[NSString stringWithFormat:@"/%@.png", [postsArrayID objectAtIndex:indexPath.row]]]]; 

// If image contains anything, set cellImage to image. If image is empty, try one more time or use noImage.png, set in IB 
if (image != nil){ 
    // If image != nil, set cellImage to that image 
    cell.cellImage.image = image; 
} 
image = nil; 
[image release]; 

(类细胞(自定义表格视图单元格)也释放cellImage在dealloc方法)。

我还没有知道它为什么会泄漏的线索,但它当然是。 图像在cellForRowAtIndexPath:-方法中多次加载。前三个单元格的图像不会泄漏(130px高,所有空间都可用)。

泄漏给我没有其他信息比那个UIImage allocated here in the code leaks

你能帮我弄明白吗?谢谢:)

+0

,你会在这种情况下使用什么样的?这两者之间有什么区别:[[UIImage alloc] initWithContentsOfFile:...];和[UIImage imageWithContentsOfFile:...] ;.有没有什么区别? – Emil 2010-06-02 20:29:04

回答

5

你就不会有正确的,如果图像是一个@property的代码。您可以通过执行self.property = nil来释放@property,因为setter的工作方式。 setter释放旧对象并将ivar设置为该值。为了解决这个问题,你需要先放[image release]。这里发生的是,你将图像设置为零,然后你基本上在做[nil release]。旧图像只是浮在某处。因此,要解决这个问题做到以下几点:

[image release]; 
image = nil; 
+0

很好的解释。谢谢。 – Emil 2010-06-02 20:27:48

+0

噢,无论如何将释放对象设置为'nil'有什么意义? – Emil 2010-06-02 20:28:45

+0

主要原因是因为如果你是由于某种原因调用它的方法,它将不会像EXC_BAD_ACCESS那样返回。如果您向已发布的对象发送消息,则只有当@property的setter语义为“retain”时,您的应用才会因EXC_BAD_ACCESS而崩溃,原因是 – rickharrison 2010-06-02 20:35:58

3

在致电release之前,您将它设置为nil。所以你正在发布nil而不是image

变化来自:

image = nil; 
[image release]; 

到:

[image release]; 
image = nil; 
+0

哦,我没有意识到这可能会导致泄漏..!谢谢:) – Emil 2010-06-02 20:25:35

+0

你会在这种情况下使用什么?这两者之间有什么区别:'[[UIImage alloc] initWithContentsOfFile:...];''和'[UIImage imageWithContentsOfFile:...];'。有没有什么区别? – Emil 2010-06-02 20:26:47

+1

不是我真的知道的。 'imageWithContentsOfFile'是一种方便的方法。所以它负责释放图像。如果你调用alloc,那么你有责任。你可以在这里的苹果内存管理指南阅读有关它:http://developer.apple.com/mac/library/documentation/cocoa/Conceptual/MemoryMgmt/MemoryMgmt.html – 2010-06-02 20:29:27

0

点点代码修改

UIImage *image = [[UIImage alloc] initWithContentsOfFile:[imagesPath 
     stringByAppendingPathComponent:[NSString stringWithFormat:@"/%@.png", 
     [postsArrayID objectAtIndex:indexPath.row]]]]; 

if (image){ 
    cell.cellImage.image = image; 
    [image release];