我不明白为什么这次没有更新。整天都在看。我不知道是否与成为我的第一个MacOs项目有关,也许有一些事情在逃避我,但我希望获得帮助。
import Cocoa
class TextViewController: NSViewController {
@IBOutlet weak var text: NSScrollView!
@IBOutlet weak var dreadline: NSTextField!
var seconds: Int = 60
var timer: Timer?
var theWork = Dreadline(email: "", worktime: 0)
override func viewDidLoad() {
super.viewDidLoad()
print(seconds)
let timer = Timer.scheduledTimer(withTimeInterval: 1.0, repeats: true) { timer in
print(self.seconds)
self.updateTimer()
} // this is the timer that doesn't work no matter what I try :(
}
@objc func updateTimer() {
if seconds < 1 {
timer?.invalidate()
} else {
seconds -= 1 //This will decrement(count down)the seconds.
dreadline.stringValue = "Dreadline: " + timeString(time: TimeInterval(seconds)) //This will update the label.
}
}
答案 0 :(得分:2)
一个非常常见的错误:您正在创建一个与声明的属性不同的 local 计时器。
替换
let timer = Timer.scheduledTimer(withTimeInterval: 1.0, repeats: true) { timer in
print(self.seconds)
self.updateTimer()
} // this is the timer that doesn't work no matter what I try :(
使用
self.timer = Timer.scheduledTimer(withTimeInterval: 1.0, repeats: true) { timer in
print(self.seconds)
self.updateTimer()
} // this is the timer that doesn't work no matter what I try :(
self
之前的timer
实际上不是强制性的。
并在无效后将计时器设置为nil
,以避免保留周期
if seconds < 1 {
timer?.invalidate()
timer = nil
}
另一方面,您可以使用 local 计时器,方法是删除该属性并将代码更改为
Timer.scheduledTimer(withTimeInterval: 1.0, repeats: true) { timer in
print(self.seconds)
self.updateTimer(timer)
}
func updateTimer(_ timer : Timer) {
if seconds < 1 {
timer.invalidate()
} else {
seconds -= 1 //This will decrement(count down)the seconds.
dreadline.stringValue = "Dreadline: " + timeString(time: TimeInterval(seconds)) //This will update the label.
}
}