我在项目中使用NSTimer:
var clickTimer: Timer?
override func mouseDown(with event: NSEvent) {
clickTimer = Timer.scheduledTimer(timeInterval: 2.0, target: self, selector: #selector(close(timer:)), userInfo: nil, repeats: false)
}
然后我在其中使它无效
override func mouseUp(with event: NSEvent) {
if let timer = self.clickTimer {
timer.invalidate()
}
}
mouseUp
内的代码正在运行,但计时器的close
方法仍在2秒内运行。为什么无效无效?
答案 0 :(得分:2)
我现在看到了。,您不想重新声明您的clickTimer
,所以您要做的就是
if (self.clickTimer == nil) {
self.clickTimer = Timer.scheduledTimer(timeInterval: 2.0, target: self, selector: #selector(close(timer:)), userInfo: nil, repeats: false)
}
只是想一想,您多次重新初始化clicktimer,先前的成功成功了,但是您不小心重新声明了一个新的计时器.. hmm ..
为了安全起见,我还建议您在self.clickTimer = nil
之后添加timer.invalidate()
答案 1 :(得分:0)
您使self.clickTimer的实例无效,应该使self.clickTimer无效
override func mouseUp(with event: NSEvent) {
if let timer = self.clickTimer {
self.clickTimer.invalidate()
}
}
我知道,您没有触发clickTimer!首先,如果要执行此操作,则必须触发此变量-> clickTimer.fire()
然后,当您希望无效时,
'Timer.scheduledTimer(timeInterval: 2.0, target: self, selector: #selector(close(timer:)), userInfo: nil, repeats: false)
当您要声明clickTimer而不是要使其无效时自动运行!!!
答案 2 :(得分:0)
尝试此代码,首先使其无效,然后删除引用。
override func mouseUp(with event: NSEvent) {
self.clickTimer?.invalidate()
self.clickTimer = nil
}
答案 3 :(得分:0)
多次调用mouseDown(with:)
时会出现问题,原来的计时器将被替换,因此,您没有引用使其无效。
var clickTimer: Timer?
override func mouseDown(with event: NSEvent) {
clickTimer?.invalidate()
clickTimer = Timer.scheduledTimer(timeInterval: 2.0, target: self, selector: #selector(close(timer:)), userInfo: nil, repeats: false)
}
override func mouseUp(with event: NSEvent) {
clickTimer?.invalidate()
}
答案 4 :(得分:0)
尝试一下
私有变量clickTimer:NSTimer?
func functionname() {
guard clickTimer == nil else { return }
clickTimer = NSTimer.scheduledTimerWithTimeInterval(15, target: self, selector: "fetchWallPosts", userInfo: nil, repeats: true)
}
或
self. clickTimer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: (#selector(yourmethod)), userInfo: nil, repeats: true)
答案 5 :(得分:0)
尝试-
if (self.clickTimer == nil) {
self.clickTimer = Timer.scheduledTimer(timeInterval: 2.0, target: self, selector: #selector(close(timer:)), userInfo: nil, repeats: false)
}