定时器在Swift 4的可可/ mac OS中不起作用

时间:2019-01-29 20:33:20

标签: swift macos cocoa nstimer

我不明白为什么这次没有更新。整天都在看。我不知道是否与成为我的第一个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.
    }
}

1 个答案:

答案 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.
    }
}