使 NSTimer 无效? [英] Invalidating an NSTimer?

查看:71
本文介绍了使 NSTimer 无效?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有一个在 viewdidload 中启动的 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?

推荐答案

如果你创建一个带有 NSTimer 的定时器 scheduleTimerWithTimeInterval... 那么你不需要释放它,因为你不拥有它.

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

现在重要的是定时器类保留了目标,大多数情况下我们使用 self 作为目标.如果计时器不是重复的,那么在计时器处理程序完成后,它会自动变为无效并释放目标.所以你无事可做.但是,如果您的计时器在离开视图时仍处于挂起状态(如果您在计时器触发之前离开或计时器重复时会发生这种情况),那么您需要使其无效.这个地方不能是 dealloc 方法.由于计时器本身保留了目标,因此在计时器无效之前不会调用 dealloc.

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.

这篇关于使 NSTimer 无效?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆