2011-10-05 154 views
3

我想將所有照片從資產保存到某個文件夾。這樣做循環:Objective-C imageWithCGImage內存泄漏

ALAssetRepresentation *representation = [asset defaultRepresentation]; 
CGImageRef imageRef = [representation fullResolutionImage]; 

ALAssetOrientation orientation = [representation orientation]; 
UIImage *image = [UIImage imageWithCGImage:imageRef scale:1.0 orientation:(UIImageOrientation)orientation]; 

CGFloat compressionQuality = 1.0; 
NSData *imageData = [NSData dataWithData:UIImageJPEGRepresentation(image, compressionQuality)]; 
[imageData writeToFile:path atomically:YES]; 

CGImageRelease(imageRef); 

我已啓用自動引用計數。此代碼位於autorelease池內。它有一個CGImageRef對象的內存泄漏。如果我將製作

CGImageRelease(imageRef); 
CGImageRelease(imageRef); 

兩次沒有內存泄漏。爲什麼?任何人都可以幫助我?

回答

8

這是iOS中的一個令人難以置信的錯誤。顯然,當你使用imageWithCGImage:方法創建UIImage時,它保留了原始的CGImageRef,即使你釋放UIImage本身也不會釋放它(例如,如果你使用ARC,將它設置爲nil)!所以你必須這樣明確地發佈它:

UIImage *image = [UIImage imageWithCGImage:imageRef scale:1.0 orientation:(UIImageOrientation)orientation]; 
CGImageRelease(imageRef); 
... 
CGImageRelease(image.CGImage); 
image = nil; // once you are done with it 

花費我整天的挖掘,直到我遇到這個問題,實際上包含答案。我可以在Apple花費在調試這個無法形容的錯誤上的時間,向誰發送賬單?

更正:這不是一個iOS錯誤,這是我的愚蠢的錯誤。在某些時候,我通過一個私人類別「劫持」dealloc UIImage的方法來做一些調試並忘記了它。這是一個錯誤的事情,因爲在這種情況下,實際對象的dealloc永遠不會被調用。所以最終的結果是預期的:UIImage沒有機會完成它在被釋放時應該做的所有內務。永遠不要通過私人類別來覆蓋dealloc。

+0

這救了我的命。 –