如何检查NSTimer是否已经失效 [英] How to check if NSTimer has been already invalidated
问题描述
我有一个 NSTimer
对象,如果用户点击按钮或者退出视图,我需要使其无效。
I have a NSTimer
object that I need to invalidate if a user taps on a button or if they exit a view.
所以我有:
[myNSTimer invalidate];
在我的按钮处理程序内部 viewWillDisappear
。如果用户点击按钮,然后存在一个视图,应用程序会抛出异常,因为 myNSTimer
已经失效。
我在 viewWillDisappear
方法中需要做的是检查 myNSTimer
是否已失效。
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?
我试过:
if(myNSTimer != nil)
[myNSTimer invalidate];
但不起作用。
推荐答案
一旦你使计时器无效,只需调用 release
就可以了(假设你保留了你所持有的引用)然后nil出你的参考。这样,当你退出视图,试图使计时器无效第二次将调用该方法在nil,而不做任何事情。
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.
或者,您可以使用 - [NSTimer isValid]
来检查它是否在无效之前是有效的,但是真的没有理由在第一次无效之后保留你的引用。另外,如果你的真正的问题是你没有保留你的引用,所以第一个 -invalidate
实际上留给你一个指向释放对象的引用,然后调用 -isValid
将无法帮助。
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.
这篇关于如何检查NSTimer是否已经失效的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!