开发者

Invalidating an NSTimer?

开发者 https://www.devze.com 2023-01-11 16:36 出处:网络
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?If you create a timer with

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?


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消