標籤:
ARC模式下的記憶體泄露問題
iOS提供的ARC 功能很大程度上簡化了編程,讓記憶體管理變得越來越簡單,但是ARC並不是說不會發生記憶體泄露,使用不當照樣會發生。
以下列舉兩種記憶體泄露情況:死迴圈造成的記憶體泄露
-
若一個ViewController中存在無限迴圈,就會導致即使ViewController所對應的View消失掉了,ViewController對象也不能夠被釋放。
此問題通常發生在animation處理中:
eg:
CATransition *transition = [CATransition animation]; transition.duration = 0.5; tansition.repeatCount = HUGE_VALL; [self.view.layer addAnimation:transition forKey:"myAnimation"];
以上樣本中,animation重複設成HUGE_VALL(一個很大的數值),基本上等於無限迴圈了。
解決的辦法是:當ViewController關掉的時候,停止這個animation。
eg:
-(void)viewWillDisappear:(BOOL)animated { [self.view.layer removeAllAnimations]; }
迴圈參照造成的記憶體泄露
-
甲有一個屬性參照為乙,乙有個屬性參照為甲,如果甲和乙都為strong參照的話,兩個對象都是無法釋放的。
這種問題通常發生於把delegate聲明為strong屬性了。
eg:
@interface ExampleViewController @property (nonatomic, strong) ExampleClass *exampleClass; @end @interface ExampleClass @property (nonatomic, strong) ExampleViewController *delegate; @end
以上這種問題解決辦法只需把ExampleClass的delegate屬性的strong改為assign即可。
ARC模式下的記憶體泄露問題