Haru
Haru

Reputation: 65

Timer doesn't stop on swift

Now I learn Timer(), i could succeed to fire it but it doesn't stop even i call invalidate().How can i solve this? I use Xcode 11.1.

I'll show some codes and the log.

This is ContentView.swift, just edit to have a button from default. ContentView.swift

import SwiftUI

struct ContentView: View {
    var body: some View {
        Button(action: {
            // What to perform
            let timerFire = TimerFire()
            timerFire.FireTimer()
        }) {
            // How the button looks like
            Text("Button")
        }
    }
}

This is TimerFire.swift. It does timer fire, then if timer count comes 5,it supposed to stops timer TimerFire.swift

import Foundation
import UIKit
import SwiftUI
let TIME_MOVENEXT = 5
var timerCount : Int = 0

class TimerFire : ObservableObject{
    var workingTimer = Timer()

    @objc func FireTimer() {
        print("FireTimer")
        var workingTimer = Timer()
        workingTimer = Timer.scheduledTimer(timeInterval: 1,      
            target: self,                                         
            selector: #selector(TimerFire.timerUpdate),      
            userInfo: nil,                                   
            repeats: true)                                   
    }

    @objc func timerUpdate(timeCount: Int) {
        timerCount += 1
        let timerText = "timerCount:\(timerCount)"
        print(timerText)

        if timerCount == TIME_MOVENEXT {
            print("timerCount == TIME_MOVENEXT")

            workingTimer.invalidate()     //here i call invalidate(), but it doesn't stop
            print("workingTimer.invalidate()")
        }
    }
}

Here is the log i run this code. log

timerCount:1
timerCount:2
timerCount:3
timerCount:4
timerCount:5
timerCount == TIME_MOVENEXT
workingTimer.invalidate()
timerCount:6
timerCount:7

After call workingTimer.invalidate(), timer still works. could someone help me?

Upvotes: 0

Views: 557

Answers (1)

Kishan Bhatiya
Kishan Bhatiya

Reputation: 2368

you are creating another instance of timer inside FireTimer() function with same name, just remove and try

Upvotes: 3

Related Questions