简体   繁体   中英

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?

您正在FireTimer()函数中创建另一个具有相同名称的计时器实例,只需删除并尝试

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM