views:

95

answers:

2

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?

A: 

http://stackoverflow.com/questions/1171290/problems-in-nstimer-release-or-invalidate

Aaron Saunders
Thanks, quick question if I used checkeventsTimer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(checkEvents) userInfo:nil repeats:YES]; Does this mean I need to release it or just invalidate it?
NextRev
+1  A: 

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.

taskinoor
You *always* need to invalidate the timer. If you set (say) a 10-second timer, the user has plenty of time to navigate away from the view before the timer fires. Otherwise, the answer is mostly accurate.
tc.
this is exactly what i have mean by "this happens if you leave before the timer is fired". and invalidating a timer which is already invalid does not cause any problem.
taskinoor
i dont need to always invalidate the timer. this depends on the situation. why do i need to invalidate it if im sure that user have nothing to do until the non-repetitive timer is fired. say im enabling user interaction after the timer is fired. do i still need to invalidate it? i know invalidating will not cause any problem, but technically i dont need to invalidate it.
taskinoor
invalidating my timers by putting them in the button handler that moves the app to another view causes EXC BAD ACCESS
NextRev
post your code. otherwise its difficult to help.
taskinoor