How to check if NSTimer has been already invalidated

前端 未结 4 2021
长情又很酷
长情又很酷 2021-02-19 19:07

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];
         


        
4条回答
  •  眼角桃花
    2021-02-19 19:58

    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.

提交回复
热议问题