NSTimer 即使在尝试主线程解决方案后也不会失效



我已经设置了一个NSTimer并尝试使其失效,但计时器仍然触发选择器。我已经尝试了许多线程的建议,并在主线程上设置了计时器并使其无效。

通过在重新实例化计时器之前使计时器失效来解决此问题。

以前:

    self.timer = NSTimer.scheduledTimerWithTimeInterval(10, target: self, selector: #selector(self.hide), userInfo: nil, repeats: false)

后:

    self.timer?.invalidate()
        self.timer = NSTimer.scheduledTimerWithTimeInterval(10, target: self, selector: #selector(self.hide), userInfo: nil, repeats: false)

我遇到了同样的问题。这是唯一对我有用的东西:

启动计时器:

NSTimer.scheduledTimerWithTimeInterval(1.0, target:self, selector:#selector(timerMethod), userInfo:nil, repeats: false)

然后在计时器方法中:

func timerMethod() {
     // do what you need to do
     if (needs to be called again) {
         NSTimer.scheduledTimerWithTimeInterval(1.0, target:self, selector:#selector(timerMethod), userInfo:nil, repeats: false)        
     }
}

这是我让它工作的唯一方法。从这里摘录:NSTimer没有停止,这是Mona的答案。

如果您在单独的线程上创建了它,它不会失效。

invalidate()文档 说

必须从安装计时器的线程发送此消息。如果从另一个线程发送此消息,则可能不会从其运行循环中删除与计时器关联的输入源,这可能会阻止线程正常退出。

相关内容

最新更新