即使在尝试主线程解决方案后,NSTimer 也不会失效
NSTimer not invalidating even after trying main thread solution
我已经设置了一个 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)
然后在timerMethod中:
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 doesn't stop 这是莫娜的回答。
如果您在单独的线程上创建它,它不会失效。
invalidate()
的文档说
You must send this message from the thread on which the timer was installed. If you send this message from another thread, the input source associated with the timer may not be removed from its run loop, which could prevent the thread from exiting properly.
我已经设置了一个 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)
然后在timerMethod中:
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 doesn't stop 这是莫娜的回答。
如果您在单独的线程上创建它,它不会失效。
invalidate()
的文档说
You must send this message from the thread on which the timer was installed. If you send this message from another thread, the input source associated with the timer may not be removed from its run loop, which could prevent the thread from exiting properly.