I am trying to invalidate a Timer which is created multiple times in a class. Firstly I create a global Timer;
var musicTimer: Timer?
And I initiate it.
self.musicTimer = Timer.scheduledTimer(
timeInterval: 2.0,
target: self,
selector: #selector(startMusicOnCorrectTime),
userInfo: nil,
repeats: true)
Then somehow I need to invalidate the timer because I need to stop calling a function.
self.musicTimer?.invalidate()
And then I need to recreate this timer with the same parameters.
self.musicTimer = Timer.scheduledTimer(
timeInterval: 2.0,
target: self,
selector: #selector(startMusicOnCorrectTime),
userInfo: nil,
repeats: true)
But this time when I need to invalidate it, I cannot. During the class lifecycle, I need this sequence multiple times and the amount is not exact.
Hard to say without a full code example, but here's an idea. In case you are calling
invalidatefrom a different thread than you started it on (e.g. you start it on the main thread but invalidate it on a background thread), it won't work according to the docs: