0

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?

2
  • You are creating another instance of Timer inside the FireTimer function on top of the class variable with the same name. Commented Dec 25, 2019 at 3:02
  • Ohhhhhh, man. Thanks for giving me the solution...! Commented Dec 25, 2019 at 3:06

1 Answer 1

3

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.