2013-12-23 81 views
0

我很困惑,爲什麼當我調用removeFromSuperview內存分配給已移除的視圖不釋放。所以這裏是我的代碼和測試結果的一部分。 我有在uiscrollview上添加的uiscrollview和uiview。所以當我滾動我的uiscrollview我調用removefromsuperview並期待內存將被釋放。removefromsuperview不釋放內存

-(void) someFunction { 
magazineContentView = [[MagazineContentView alloc] initWithFrame:CGRectMake(35 + 320 *i ,0,self.view.frame.size.width,self.view.frame.size.height)]; 
[_scrollView addSubview:magazineContentView]; 
} 
-(void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView { 
[magazineContentView removeFromSuperview]; 
magazineContentView = nil; 
} 

magazineContentView正確刪除但內存不減少。

我沒有使用ARC。

謝謝。

+0

您是否在使用ARC?你在哪裏檢查內存沒有減少?儀器?請在你的問題中包含所有相關的細節。 – Sid

+0

感謝重播, 不,我不使用ARC。我正在使用標準的xcode內存報告。我添加屏幕,你可以在分配之前看到內存大小,添加視圖後添加uiview是8.5 MB,它變成了9MB,但從uiscrollview刪除此視圖後仍然保持9MB!哎呀抱歉,我無法在此刻添加屏幕,我沒有權限。 – Sergo

回答

1

當您分配magazineContentView並將其添加爲子視圖時,它將被保留兩次。由於您使用的是手動保留版本,而不是使用ARC,因此您需要在將其添加爲子視圖後的某個時候發佈它。

[magazineContentView removeFromSuperview]只會使保留計數減少1.由於init調用,仍有一個保留實例。 (僅供參考,我在此提及,以更好地解釋我的答案)。

此外,直接設置你的伊娃像你這樣做沒有真正的幫助,因爲它不是一個屬性。

您也不應該在didEndDecelerating調用中從超級視圖中刪除。這是不好的做法。您已將它設置爲零,因此調用removeFromSuperview不會損害任何內容,但這不是好的代碼設計。

爲什麼不使用ARC?它使用起來更清潔。

如果您堅持使用MRR,您應該在將它作爲子視圖添加後,在magazineContentView上調用發佈。這樣,當您稍後調用removeFromSuperview時,保留和釋放會保持平衡。

-(void) someFunction { 
magazineContentView = [[MagazineContentView alloc] initWithFrame:CGRectMake(35 + 320 *i ,0,self.view.frame.size.width,self.view.frame.size.height)]; 
[_scrollView addSubview:magazineContentView]; 
[magazineContentView release]; 
} 
-(void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView { 
// Move these to some other place... e.g. a separate method that does this only once 
[magazineContentView removeFromSuperview]; 
magazineContentView = nil; 
} 

此外,你應該首先更密切地關注泄漏,那麼你應該看看分配測量。

您是否看過Apple提供的內存管理指南?這是您花時間閱讀本文檔並理解MRR的好時機 - https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/MemoryMgmt/Articles/MemoryMgmt.html