2010-06-19 121 views
3

我的iPhone應用程序從服務器下載圖像文件,將其存儲到NSTemporaryDirectory()中,然後異步加載UI中的圖像。代碼流是這樣的:UIGraphicsGetImageFromCurrentImageContext縮放圖像的內存泄漏

  1. 顯示視圖與加載活動指標,並在後臺運行圖像下載。
  2. 圖像下載完成後,會寫入文件。
  3. 加載視圖中的計時器會繼續檢查臨時目錄中文件的可用性,一旦可用,就從文件加載圖像並將圖像添加到UI。
  4. 添加圖像之前,它會縮放到所需的大小。

問題是,我使用UIGraphicsGetImageFromCurrentImageContext來縮放圖像。看起來圖像上下文使用的內存沒有被清理。隨着更多文件被下載,應用程序內存不斷增加。

一些以下代碼:

代碼以縮放圖像:


-(UIImage*)scaleToSize:(CGSize)size image:(UIImage *)imageref 
{ 
UIGraphicsBeginImageContext(size); 
[imageref drawInRect:CGRectMake(0, 0, size.width, size.height)]; 
UIImage* scaledImage = UIGraphicsGetImageFromCurrentImageContext(); 
UIGraphicsEndImageContext(); 
return scaledImage; 
} 

加載圖像從臨時目錄:


-(void)loadImageFromFile: (NSString *) path 
{ 
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init]; 
UIImage * imm = [[[UIImage alloc] initWithContentsOfFile:path] autorelease]; 
[self performSelectorOnMainThread:@selector(insertImage:) withObject:imm waitUntilDone:YES]; 
[pool release]; 
} 

添加圖片查看(的子集代碼):


self.imageContainer = [[UIImageView alloc] initWithFrame:CGRectMake(0,80,320,250)]; 
[self addSubview:self.imageContainer]; 
self.imageContainer.image = [self scaleToSize:CGSizeMake(320.0f, 250.0f) image:imm]; 
[imageContainer release]; 

我在這裏錯過了什麼?從UIGraphicsGetImageFromCurrentImageContext避免泄漏的

+0

你刪除子視圖呢?你覺得你泄漏了多少內存?也許從網上加載是你的問題?是什麼讓你認爲縮放是你的問題? – Eiko 2010-06-19 12:31:24

+0

感謝您的回覆。進一步的調查顯示,縮放並不是真正的問題。這是UI圖像實例沒有得到清理。任何線索,爲什麼它可能是這種情況? – KSH 2010-06-21 07:49:31

+0

你有沒有找到這個決議?我目前有同樣的問題:'UIImage'創建'UIGraphicsGetImageFromCurrentImageContext()'泄漏內存。 – MusiGenesis 2011-12-07 15:58:31

回答

0

一種方式是不是通過調整容器,而不是直接調整圖像都叫它:

self.imageContainer.contentMode = UIViewContentModeScaleAspectFit; 
self.imageContainer.frame = CGRectMake(self.imageContainer.frame.origin.x, self.imageContainer.frame.origin.y, 320.0f, 250.0f);