2011-03-30 51 views
1

我有以下代碼:CGImage/UIImage的泄漏

... 

UIImage *image; 
CGImageRef imageRef; 

image = [[[UIImage alloc] initWithContentsOfFile: filePath] retain]; 

while (some_condition) 
{ 
    NSAutoreleasePool *pool = [[NSAutoReleasePool alloc] init]; 

    imageCGDATA = CGDataProviderCreateWithCFData(cfdata); 

    imageRef = CGImageCreate(width, height, bitsPerComponent, bitsPerPixel, bytesPerRow, colorSpace, bitmapInfo, imageCGDATA, NULL, NO, intent); 

    CGDataProviderRelease(imageCGDATA); 

    [image release]; 

    image = [[[UIImage alloc] initWithCGImage: imageRef]] retain]; // LEAK HERE 

    CGImageRelease(imageRef); 

    [pool release]; 
} 

... 

當我運行的代碼,並期待在分配我看到總的「活字節」成長爲循環的每個迭代完成,並數「 CGImage「和」UIImage「Living分配增長到非常大的數字(顯然取決於循環的迭代次數)。

如果我評論用「LEAK HERE」註釋的代碼行(以及緊接在該代碼行之前的版本)並重新運行應用程序,那麼「Live Bytes」,「CGImage」和「UIImage」生命分配在循環的許多迭代中保持靜態。

爲什麼該代碼泄漏?我錯過了什麼?

謝謝。

回答

0

您不需要保留:

image = [[[UIImage alloc] initWithCGImage: imageRef]] retain];

你打電話alloc,所以返回的對象已經具有1的retainCount保留它再次遞增retainCount爲2,但你在你重新指定下一個循環迭代的指針之前,只釋放它一次。因此,實例泄漏,因爲retainCount留在1

所以長話短說,這應該修復它:

image = [[UIImage alloc] initWithCGImage: imageRef]];

+0

謝謝!不能相信我錯過了 - 我是Objective-C的新手,我掩飾了這一點...... – JeffR 2011-03-30 07:00:28