views:

73

answers:

2
[NSTimer scheduledTimerWithTimeInterval:0.033 target:self selector:@selector(gameLoop)
     userInfo:nil repeats:YES];

I don't do anything to dealloc or kill this timer after starting it. Is it safe? Or will it cause me to leak memory?

+4  A: 

It shouldn't leak memory. You're not retaining the timer. The run loop will retain it (I think), but it'll release it when it no longer needs it.

mipadi
Yeah, the run loop will retain timers when they're scheduled.
Wevah
Timers also retain their target. Therefore if an object that is also the timers target retains the timer, a retain cycle is formed.
Jasarien
Yes, timers will retain their target. So, It will mean timer always fire before target deallcated.
Toro
+2  A: 

The timer is retained by the run loop, so you don't need to retain it yourself.

However the timer will retain its target, so as long as it's repeating and you don't invalidate it, your target object won't be deallocated. You'll need to choose a good time to call invalidate on it which will cause the run loop to release it.

Note that you shouldn't also retain the timer yourself, at the risk of a retain cycle.

(I borked an answer to this very question yesterday and got schooled on it. Trying to atone.)

quixoto
Ok i see this used in the GKTank sample application/code. It never gets set to invalidate. Is apple giving sample code thats bad? I try to learn from these samples -.-
Code