How to “validate” a NSTimer after invalidating it?

2020-08-09 06:34发布

问题:

So basically, I have this timer that should be repeated when it receives a key event, and invalidates when the user releases the key. However, I am unable to "validate" the timer back even by calling the addTimer:forMode: in NSRunLoop. Does anyone know why this is happening and how I can fix this? Thanks.

回答1:

You cannot use invalidated timer.

From Apple Docs:

Once scheduled on a run loop, the timer fires at the specified interval until it is invalidated. A non-repeating timer invalidates itself immediately after it fires. However, for a repeating timer, you must invalidate the timer object yourself by calling its invalidate method. Calling this method requests the removal of the timer from the current run loop; as a result, you should always call the invalidate method from the same thread on which the timer was installed. Invalidating the timer immediately disables it so that it no longer affects the run loop. The run loop then removes and releases the timer, either just before the invalidate method returns or at some later point. Once invalidated, timer objects cannot be reused.



回答2:

Once you've invalidated an NSTimer, you shouldn't use it again.

Instead, create a new timer instance, and use that instance to add to the NSRunLoop's addTimer method. Personally I prefer just calling NSTimer's scheduledTimerWithTimeInterval because it does everything in one shot.

From NSTimer docs:

Calling this method requests the removal of the timer from the current run loop; as a result, you should always call the invalidate method from the same thread on which the timer was installed. Invalidating the timer immediately disables it so that it no longer affects the run loop. The run loop then removes and releases the timer, either just before the invalidate method returns or at some later point. Once invalidated, timer objects cannot be reused.