Invalidating an NSTimer?

泄露秘密 提交于 2019-12-24 14:57:20

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/3499040/invalidating-an-nstimer

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!