We call startTimer function to start a timer. When we wanted to stop it we call stopTimerTest function but after we called stopTimer function the timerTestAction keeps firing. To check the timer condition we used print and print in timerActionTest returns nil.
var timerTest: Timer? = nil
func startTimer () {
timerTest = Timer.scheduledTimer(
timeInterval: TimeInterval(0.3),
target : self,
selector : #selector(ViewController.timerActionTest),
userInfo : nil,
repeats : true)
}
func timerActionTest() {
print(" timer condition \(timerTest)")
}
func stopTimerTest() {
timerTest.invalidate()
timerTest = nil
}
Most likely you've called
startTimer
twice without callingstopTimerTest
. If you do that, you'll lose your pointer to the original timer and never be able to invalidate it.The typical approach is to manage invalidation as a part of setting:
Then stopping is just setting to nil:
Check, are you really call
stopTimerTest()
, becausetimerTest.invalidate()
is correct for stopping timer.Try to make the following changes to your code:
First, you have to change the way you declare
timerTest
then in
startTimer
before instantiating check iftimerTest
is nilFinally in your
stopTimerTest
you invalidatetimerTest
if it isn't nil