I have this problem for a few days now and I don\'t get what I am doing wrong.
My application is basically just creating some timers. I need to stop them and create
The usual way to start and stop a timer safely is
var timer : NSTimer?
func startTimer()
{
if timer == nil {
timer = NSTimer.scheduledTimerWithTimeInterval(timeInterval, target: self, selector: "timerFired", userInfo: nil, repeats: true)
}
}
func stopTimer()
{
if timer != nil {
timer!.invalidate()
timer = nil
}
}
startTimer()
starts the timer only if it's nil
and stopTimer()
stops it only if it's not nil
.
You have only to take care of stopping the timer before creating/starting a new one.
In Swift 3 replace
NSTimer
with Timer
, NSTimer.scheduledTimerWithTimeInterval(
with Timer.scheduledTimer(timeInterval:
selector: "timerFired"
with selector: #selector(timerFired)
.Something that's not really covered by the previous answers is that you should be careful your timer isn't scheduled multiple times.
If you schedule a timer multiple times without first invalidating it, it'll end up scheduled on multiple run loops, and invalidating it then becomes nigh impossible.
For me, it happened when calling my scheduleTimer()
function in separate functions in my view controller's life cycle (viewWillAppear
, viewDidAppear
, ...)
So in short, if you aren't sure (or you cannot guarantee) your Timer is only scheduled once, just always invalidate it first.
Make sure you're calling invalidate on the same thread as the timer.
From the documentation:
Special Considerations You must send this message from the thread on which the timer was installed. If you send this message from another thread, the input source associated with the timer may not be removed from its run loop, which could prevent the thread from exiting properly.
https://developer.apple.com/documentation/foundation/nstimer/1415405-invalidate?language=objc