简体   繁体   English

如何使ViewDidLoad外的计时器无效

[英]How to invalidate timer outside ViewDidLoad

I'm stuck with invalidating timer outside of ViewDidLoad. 我被困在ViewDidLoad之外使计时器失效。 Tried to declare timer globally, but got a SIGABRT error. 试图全局声明计时器,但收到SIGABRT错误。 What am am I missing? 我想念什么?

override func viewDidAppear(_ animated: Bool) {

    let timer = Timer(timeInterval: 3, 
                      target: self, 
                      selector: #selector(updateOnlineTrack), 
                      userInfo: nil, 
                      repeats: true)

    RunLoop.current.add(timer, forMode: .defaultRunLoopMode)
    timer.fire()

}

updateOnlineTrack is marked with @objc and project is compiling, but I can't figure out this SIGABRT updateOnlineTrack标记有@objc,并且项目正在编译,但是我不知道此SIGABRT

@objc private func updateOnlineTrack() {

    print("Tick")

}

Basically I need to invalidate timer and stop updating, when user leaves current View Controller. 基本上,当用户离开当前的View Controller时,我需要使计时器无效并停止更新。

Any help is appreciated 任何帮助表示赞赏

The timer is fired automatically when you init it after the specified interval , you can declare it like this 在指定的时间间隔后初始化计时器时,计时器会自动触发,您可以像这样声明它

var timer:timer?

// //

override func viewDidAppear(_ animated: Bool) {

    self.timer = Timer(timeInterval: 3, 
                  target: self, 
                  selector: #selector(updateOnlineTrack), 
                  userInfo: nil, 
                  repeats: true)

}

You need to declare timer as an instance property instead of a local variable. 您需要将timer声明为实例属性,而不是局部变量。

class MyViewController: UIViewController {
    var timer: Timer?

    override func viewDidAppear(_ animated: Bool) {
        timer = Timer.scheduledTimer(timeInterval: 3, 
                  target: self, 
                  selector: #selector(updateOnlineTrack), 
                  userInfo: nil, 
                  repeats: true)

        timer?.fire()
    }
}

Note that it is optional. 请注意,它是可选的。

Note the use of scheduledTimer . 注意使用scheduledTimer This is simpler than adding it to a runloop yourself. 这比自己将其添加到运行循环要简单。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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