How to check if NSTimer has been already invalidat

2019-04-04 15:00发布

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.

4条回答
Rolldiameter
2楼-- · 2019-04-04 15:32

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.

查看更多
Lonely孤独者°
3楼-- · 2019-04-04 15:43

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:

[myNSTimer invalidate]; 
myNSTimer = nil;

and it'll do the right thing.

查看更多
太酷不给撩
4楼-- · 2019-04-04 15:56

I have had the same problem while I was trying to pause & restart a timer. To stop it:

[timer invalidate];
[timer release];
timer = nil;

And to start/ restart it:

timer = [[NSTimer scheduledTimerWithTimeInterval:3 target:self selector:@selector(aSelector) userInfo:nil repeats:YES] retain];

Now it doesn't crash when I invalidate it.

查看更多
祖国的老花朵
5楼-- · 2019-04-04 15:56

Swift:

if timer.valid {
   timer.invalidate()
}
查看更多
登录 后发表回答