NSTimer disables dealloc in UIView

后端 未结 3 2067
日久生厌
日久生厌 2021-02-06 02:56
@interface someview:UIView{
  NSTimer* timer;
}
@end

@implementation someview

-(void)dealloc{
  NSLog(@\"dealloc someview\");
  [timer invalidate];
  timer = nil;
}
-(         


        
3条回答
  •  没有蜡笔的小新
    2021-02-06 03:00

    As mentioned above, Timers retain their targets. Until the timer is invalidated, there is a retain cycle between the timer and the view, so the view will not be deallocated.

    I would invalidate the timer when it's removed from the view hierarchy by subclassing didMoveToSuperview, this gets called by the system when there is a View-Related Change (e.g superview changes). The 'removeFromSuperview' is only called when removeFromSuperview is called on UIView

    - (void)didMoveToSuperview
    {
        [super didMoveToSuperview];
    
        if (!self.superview)
        {
            [timer invalidate];
            timer = nil;
        }
    }
    

提交回复
热议问题