如何检查 NSTimer 是否已经失效
我有一个 NSTimer 对象,如果用户点击按钮或退出视图,我需要使该对象无效。
所以我有:
[myNSTimer invalidate];
在我的按钮处理程序和 viewWillDisappear
内部。 如果用户点击按钮,然后存在视图,则应用程序会引发异常,因为 myNSTimer
已失效。 我需要在 viewWillDisappear 方法中执行的操作是检查 myNSTimer 是否已失效。 我怎么做?
我已经尝试过:
if(myNSTimer != nil)
[myNSTimer invalidate];
但这没有用。
I have a NSTimer
object that I need to invalidate if a user taps on a button or if they exit a view.
So I have:
[myNSTimer invalidate];
inside my button handler and inside viewWillDisappear
. If user taps on a button and then exists a view the app throws an exception because myNSTimer
has already been invalidated.
What I need to do in the viewWillDisappear
method is check if the myNSTimer
has been invalidated or not. How do I do that?
I've tried:
if(myNSTimer != nil)
[myNSTimer invalidate];
but that didn't work.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
一旦你使计时器无效,只需对其调用
release
(假设你已经保留了你所持有的引用),然后将你的引用清零。 这样,当您退出视图时,尝试再次使计时器无效只会在 nil 上调用该方法,而不会执行任何操作。或者,您可以使用
-[NSTimer isValid]
在无效之前检查它是否有效,但无论如何,在第一次使其无效后确实没有理由保留您的引用。 另外,如果您真正的问题是您没有保留引用,因此第一个-invalidate
实际上给您留下了指向已释放对象的引用,然后调用-isValid
无论如何都没有帮助。Once you invalidate the timer, simply call
release
on it (assuming you've retained the reference you're holding on to) and then nil out your reference. That way when you exit the view, trying to invalidate the timer a second time will just call that method on nil instead, which does nothing.Alternatively, you can use
-[NSTimer isValid]
to check if it's valid before invalidating, but there's really no reason to hold onto your reference after invalidating it the first time anyway. Also, if your real problem is that you haven't retained your reference and so the first-invalidate
actually leaves you with a reference pointing at a released object, then calling-isValid
won't help anyway.我通常做的是将保存计时器的成员变量清空,无论是在它触发时,还是在我使其无效时。 然后你就可以这样做:
它会做正确的事情。
What I usually do is nil-out the member variable holding the timer, either when it fires, or when I invalidate it. Then you can just do:
and it'll do the right thing.
当我尝试暂停和暂停时,我遇到了同样的问题。 重新启动计时器。 停止它:
并启动/重新启动它:
现在,当我使其无效时,它不会崩溃。
I have had the same problem while I was trying to pause & restart a timer. To stop it:
And to start/ restart it:
Now it doesn't crash when I invalidate it.
迅速:
Swift: