Search code examples
objective-cuiviewnstimerdeallocinvalidation

NSTimer disables dealloc in UIView


@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.


Solution

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