[英]Memory management UIImage ImageNamed
我正在使用ViewController加載很多相當大的圖像
NSUInteger nimages = 0;
for (; ; nimages++) {
NSString *nameOfImage_ = @"someName";
NSString *imageName = [NSString stringWithFormat:@"%@%d.jpg", nameOfImage_, (nimages + 1)];
image = [UIImage imageNamed:imageName];
if (image == nil) {
break;
}
UIImageView *imageView = [[UIImageView alloc] initWithImage:image];
//some other stuff....
[imageView release];
}
通常的卸載發生在帶有self.image = nil的-(void)viewDidUnload和-(void)dealloc中; 和[圖片發布];
似乎在幾次“加載”和“卸載”之后,緩存仍然增長到無法返回的地步! :)
應用崩潰了...
有任何想法嗎??? 我如何清空我的緩存? 在哪里?
謝謝
編輯:
好的,這就是我做錯了。 顯然,這段代碼解決了整個緩存問題:
image = [[UIImage imageNamed:imageName] autorelease];
自動釋放是這里的關鍵。
感謝您的回復...
謝謝大家的建議。
解:
使用ARC
和imageWithContentsOffFile
初始化圖像。
image = [UIImage imageWithContentsOfFile: [[NSBundle mainBundle] pathForResource:imageName ofType:nil]];
是的 , imageNamed
僅適用於...沒什么大不了的...
image = [[UIImage imageNamed:imageName] autorelease];
這是不正確的。 為了遵守內存管理規則,您不應釋放(或自動釋放)映像,因為您沒有分配或保留映像。 “ imageNamed”不包含“ alloc”,“ new”,“ copy”或“ retain”。
正如其他一些答案所解釋的那樣,如果要對圖像使用的內存進行更多控制,則應使用其他方法加載圖像。
imageNamed
是現實中加載圖像的一種可怕方法,除非強制執行,否則它永遠不會釋放加載的圖像並將其永久保存在緩存中。 您應該實現自己的更智能的緩存。 簡單的NSMutableDictionary
提供相同的功能,但具有更大的靈活性。
要進行更深入的討論,您可以閱讀以下內容: http : //www.alexcurylo.com/blog/2009/01/13/imagenamed-is-evil/
使用另一種方法來初始化您的圖像。 imageNamed
緩存。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.