views:

76

answers:

2

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)

+4  A: 

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"

Dave DeLong
So you should clean up the timer before you expect the object to go away.
Joshua Nozzi
@Joshua +1 that's what I said... you have to `invalidate` the timer in order to get your object `released`, which may end up triggering the `dealloc` method (just not in so many words) :)
Dave DeLong
A: 

Have you tried the handy debugger tools at your disposal? What happens if you set a breakpoint in your dealloc method? Also, you should post more context around your creation. Is it possible you're creating the timer more than once, thereby replacing the original (but not invalidating it) and leaving it out there to fire at will?

Joshua Nozzi
yep.. not reaching dealloc
dkk
I'm not creating it more than once. Only at one place, and only once.
dkk