NSTimer disables dealloc in UIView

Deadly 提交于 2019-12-20 12:38:48

问题


@interface someview:UIView{
  NSTimer* timer;
}
@end

@implementation someview

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

  timer = [NSTimer timerWithTimeInterval:2.0f target:self selector:@selector(runTimer) userInfo:nil repeats:YES];
}

@end

Releasing someview will NOT call dealloc and the timer keeps on running.

If I comment out the "timer = [NSTimer schedule...." part, dealloc will be called. Which means all the other part of my code is working properly and the timer is the culprit. The runTimer method is empty, which means it's just the timer messing with me.


回答1:


NSTimer retains the target. Therefore, the timer must be invalidated before your view is dealloc'd.




回答2:


I think the best solution when using an NSTimer inside of a UIView is to override the removeFromSuperview method;

- (void)removeFromSuperview
{
    [timer invalidate];
    timer = nil;

    [super removeFromSuperview];
}

The only thing to keep in mind here is that you need to ensure that timer is not a nil object because removeFromSuperview can also get automatically called from other UIView's super dealloc methods. You could wrap in a conditional to check.




回答3:


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;
    }
}


来源:https://stackoverflow.com/questions/5670431/nstimer-disables-dealloc-in-uiview

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!