Search code examples
iphonexcodesdknstimerinvalidation

Invalidating an NSTimer?


If I have an NSTimer that starts in viewdidload, where is the proper place to invalidate it when leaving that view? Is it also necessary to release it as well?


Solution

  • If you create a timer with NSTimer scheduledTimerWithTimeInterval... then you don't need to release it, as you don't own it.

    Now important thing is that the timer class retains the target, and in most cases we use self as the target. If the timer is not repetitive , then after the timer handler is completed, it automatically becomes invalid and the target is released. So you have nothing to do. But if your timer is still pending when leaving the view (this happens if you leave before the timer is fired or the timer is repetitive) then you need to invalidate it. The place MUST NOT be the dealloc method. As the timer itself retains the target, dealloc won't be called until the timer is invalid.

    So it's better to invalidate when you know that you no longer need this. This might be the action which moves to the other view. Say user taps a button and in the button handler you move to other view. You can invalidate in this button handler.