UIView的animation和內存釋放

應用中有這樣一個操作,向主視圖中分配一個subview,然後添加subview,再使用動畫方式退出subview,最後remove掉。
這個過程內存使用量應該時增加,減少這樣一個過程,但是在調試時,發現應用內存使用逐步增加,從不釋放。

它的實現代碼如下所示:


// 日曆視圖彈出

- (void)slideInCalView:(UITextField *)textField

{

    if (_calView==nil) {

       _calView = [[XYCalendarView allocinitWithFrame:self.view.bounds andSelectedDate:[NSDate datebottomBar:YES];

//        _calView = [[XYCalendarView alloc] initComplexGridWithFrame:self.view.bounds andSelectedDate:[NSDate date] bottomBar:YES];

        

        _calView.delegate = self;

    }

    

    _calView.frame=self.view.bounds;

    

    [self.view addSubview:_calView];

    

    [UIView animateWithDuration:0.4 delay:0 options:UIViewAnimationOptionCurveLinear animations:^{

        _calView.frame = CGRectMake(00_calView.frame.size.width_calView.frame.size.height);

    } completion:^(BOOL finished) {

        

    }];


}

//// 日曆視圖關閉 使用delegate method

- (void)slideOutCalendarView:(XYCalendarDay *)selectedTileDay

{

    [UIView animateWithDuration:.5 delay:0 options:UIViewAnimationOptionCurveLinear animations:^{

        _calView.frame = CGRectMake(0_calView.frame.size.height_calView.frame.size.width_calView.frame.size.height);

    } completion:^(BOOL finished) {

        [_calView removeFromSuperview];


    }];

    

    NSDateFormatter *dateFormatter = [[NSDateFormatter allocinit];

    [dateFormatter setDateFormat:@"yyyyMMdd"];

    NSString *strDate = [dateFormatter stringFromDate:selectedTileDay.calDate];

    

    //    GTMLoggerDebug(@"selectedTileDate is %@", strDate);

    

    _editingTextField.text=strDate;

    

    _calView=nil;

    

}



這個錯誤很隱蔽。
在視圖劃出屏幕下方後,界面已經看不到。正因爲採用了劃出動畫操作,所以,將該視圖設置爲nil時,動畫還沒結束,導致動畫結束時的removeFromSuperview發送給來一個nil對象。
所以該子視圖還在主視圖上,內存還佔用。
將nil操作放到動畫完成後執行,則內存恢復正常。


    [UIView animateWithDuration:.5 delay:0 options:UIViewAnimationOptionCurveLinear animations:^{

        _calView.frame = CGRectMake(0_calView.frame.size.height_calView.frame.size.width_calView.frame.size.height);

    } completion:^(BOOL finished) {

        [_calView removeFromSuperview];

        NSDateFormatter *dateFormatter = [[NSDateFormatter allocinit];

        [dateFormatter setDateFormat:@"yyyyMMdd"];

        NSString *strDate = [dateFormatter stringFromDate:selectedTileDay.calDate];

        

        //    GTMLoggerDebug(@"selectedTileDate is %@", strDate);

        

        _editingTextField.text=strDate;

        

        _calView=nil;

    }];



奇怪的一點是,釋放內存的代碼是removeFromSuperview 而不是nil.


不對,還是nil釋放內存,只是沒有remove掉,表示還有對象在使用它,所以nil時不釋放內存。


這裏是沒有remove掉,那麼nil也不會成功。


subview設置爲nil後,卻沒有removefromsuperview,那麼佔有的內存還在。這就導致來內存泄漏。

非常隱蔽的內存泄漏。


正確的方式是:


先remove後nil纔是正確的是否內存的方式。如果還向對象繼續留在內存裏,下次調用不用定義,這在 主視圖退出時nil。


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章