UIView內存釋放,以前一直覺得把alloc的UIView對象,最後release掉或者removeFromSuperview掉就能夠了。可是最近項目中出現了當釋放父試圖時,子視圖的內存不釋放,最後致使內存泄漏,報內存警告最後程序崩潰。動畫
形成UIview內存泄漏的緣由是,當釋放UIView時,其子視圖中有佔有的資源沒有釋放掉,如動畫沒有結束,最後形成內存不會釋放掉。code
下面的代碼可以很好的展現上述過程:orm
在主視圖上添加一個AnimationView,而後在AnimationView中在添加一個視圖:對象
Animations *animationView=[[Animations alloc] initWithFrame:CGRectMake(10, 10, 270, 400)]; [animationView setBackgroundColor:[UIColor yellowColor]]; [self addSubview:animationView]; [animationView release];
在Animations視圖中添加一個遞歸的動畫:遞歸
- (void)wobble { NSLog(@">>>>>>>>>>>>>>>>>>"); CGFloat rotation = (kWobbleRadians * M_PI * 2) / 360.0; CGAffineTransform wobbleLeft = CGAffineTransformMakeRotation(rotation); [UIView beginAnimations:nil context:nil]; [UIView setAnimationDuration:kWobbleTime]; [UIView setAnimationDelegate:self]; self.transform = wobbleLeft; // if (!releaseFlage) { [UIView setAnimationDidStopSelector:@selector(wobble)]; // } [UIView setAnimationRepeatAutoreverses:NO]; [UIView commitAnimations]; }
因爲當前類每隔3秒鐘要執行一次遞歸,因此當在主視圖中移除AnimationView時,因爲AnimationView的子視圖動畫是一個遞歸沒有結 束,因此當前這個視圖樹不會釋放,只是再也不界面上顯示,最終形成內存泄漏。解決辦法以下,當AnimationView想要移除時,須要將其子視圖上的動 畫移除掉。個人作法是在內存
//AnimationView中添加下面方法便可: - (void)willRemoveSubview:(UIView *)subview { Animations *downBookView=(Animations *)subview; downBookView.releaseFlage=TRUE; }
這樣內存其視圖樹就會跟着釋放掉內存,從系統中完全釋放掉了。資源