[英]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?现在我学习了 Timer(),我可以成功触发它,但即使我调用 invalidate() 它也不会停止。我该如何解决这个问题? I use Xcode 11.1.我使用 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,只需编辑即可获得默认按钮。 ContentView.swift内容视图.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.这是 TimerFire.swift。 It does timer fire, then if timer count comes 5,it supposed to stops timer TimerFire.swift它确实定时器触发,然后如果定时器计数达到 5,它应该停止定时器 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.调用workingTimer.invalidate() 后,定时器仍然有效。 could someone help me?有人可以帮助我吗?
您正在FireTimer()
函数中创建另一个具有相同名称的计时器实例,只需删除并尝试
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.