簡體   English   中英

為什么這會泄漏內存? UIImage cellForRowAtIndexPath:

[英]Why is this leaking memory? UIImage `cellForRowAtIndexPath:`

Instruments的泄漏告訴我該UIImage正在泄漏:

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];

(類單元格(自定義表格視圖單元格)也會在dealloc方法中釋放cellImage)。

我不清楚它為什么泄漏,但肯定是。 圖像在cellForRowAtIndexPath: -method中多次加載。 前三個單元格的圖像不會泄漏(130px高,所有空間可用)。

泄漏給我的信息UIImage allocated here in the code leaksUIImage allocated here in the code leaks

你能幫我解決嗎? 謝謝 :)

如果image是@property那么您那里的代碼將是正確的。 由於設置程序的工作方式,您可以通過self.property = nil來釋放@property。 設置器釋放舊對象,並將ivar設置為該值。 為了解決這個問題,您需要先放置[image release] 這里發生的事情是將image設置為nil,然后實際上是在執行[nil release] 舊的圖像只是漂浮在某個地方。 因此,要解決此問題,請執行以下操作:

[image release];
image = nil;

您將其設置為nil然后再調用release 因此,您釋放的是nil而不是image

更改自:

image = nil;
[image release];

至:

[image release];
image = nil;

一點點代碼修改

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

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM