Search code examples
iphoneobjective-cnstimerdeallocinvalidation

NSTimer not stopping


I have a Class with a NSTimer *myTimer; variable. At some point I do:

myTimer = [NSTimer scheduledTimerWithTimeInterval:20 target:self selector:@selector(doStuff) userInfo:nil repeats: YES]; 

further, I have a method:

- (void)doStuff
{
  if(myTimer)
  {
    //do stuff
  }
}

and I stop my timer when the class is released through:

- (void)dealloc
{ 
 if (myTimer) { //if myTimer==nil it already has been stopped in the same way
  [myTimer invalidate];
  myTimer = nil;
 }
}

Now, the problem is that when I release the class the timer goes on and on and on firing the event anyway. Am I doing something wrong? It seems the dealloc method is never called, otherwise myTimer would be nil and even if the selector is fired it would not go into the if(myTimer)


Solution

  • This will never work, because timers retain their target, which means your dealloc method will never get invoked until after you've invalidated the timer.

    For more info, see the NSTimer documentation and this blog post on "Dangerous Cocoa Calls"