deinit 无法调用该函数

deinit cannot call the function

我想使用 deinit 版本 NSTimer,但它不能工作。我想知道如何使用 deinit

代码:

class timerView: NSObject {
    var timer:NSTimer?
    override init() {
        super.init()
        self.timer = NSTimer(fireDate: NSDate(), interval: 1, target: self, selector: "timers", userInfo: nil, repeats: true)
        NSRunLoop.currentRunLoop().addTimer(self.timer!, forMode: NSDefaultRunLoopMode)
    }
    deinit{
        self.timer = nil
    }

    func timers() -> Void {
        print("true")
    }
}

    var timeV:timerView?
    override func viewDidLoad() {
        super.viewDidLoad()
        self.timeV = timerView()
        self.timeV = nil
}

您可以直接使计时器无效:

timer.invalidate()

来自NSTimer Class Reference

... Invalidating the timer immediately disables it so that it no longer affects the run loop. The run loop then removes the timer (and the strong reference it had to the timer), either just before the invalidate method returns or at some later point. Once invalidated, timer objects cannot be reused.

这正是您在调用 dinit 时试图做的事情。

**由于答案并不令人满意,我可以尝试猜测您的问题:您在 class 中创建了计时器,但可能试图从程序中的不同位置使计时器无效。但这是行不通的,因为:

you should always call the invalidate method from the same thread on which the timer was installed.

这种情况的一个可能的解决方案是将计时器保持在它自己的状态 struct:

struct programTimer {
  static var timer: NSTimer = NSTimer()
 }