NSTimer在此函数中失效时不会停止

Ale*_*dro 2 nstimer swift

我正在尝试使用NTTimer,但它不起作用.

它从这里开始:

timer = NSTimer.scheduledTimerWithTimeInterval(0.003, target: self, selector: "openFrameAnimation", userInfo: nil, repeats: true)
Run Code Online (Sandbox Code Playgroud)

它激发了这个功能:

func openFrameAnimation(){
    Swift.print("Animation Goes... ",NSDate().timeIntervalSince1970)
    self.frame = NSRect(x: self.frame.origin.x,
        y: self.frame.origin.y-12,
        width: self.frame.width,
        height: self.frame.height + 12)
    if(self.frame.height >= self.finalFrame.height){
        Swift.print("STOP")
        self.frame = self.finalFrame
        timer.invalidate()
        // timer = nil //ERROR: nil cannot be assigned to type "NSTimer"
    }
    self.needsDisplay = true
}
Run Code Online (Sandbox Code Playgroud)

即使反复打印"STOP",计时器仍继续调用openFrameAnimation,我无法阻止它.如果验证条件,我该如何停止计时器?

日志:

[...]
*Animation Goes...  1456613095.27813
STOP
[...]
Animation Goes...  1456613095.51233
STOP
Animation Goes...  1456613095.54458
[...]
STOP
Animation Goes...  1456613095.5938
STOP*
Run Code Online (Sandbox Code Playgroud)

CFP*_*ort 11

斯威夫特4

  1. var timer = Timer()
    
    Run Code Online (Sandbox Code Playgroud)

到了班上

  1. 设置您的计时器(使用您的原始信息 - 您可能希望根据一些建议进行更改,尤其是来自@Rob的关于帧速率的建议)

    timer = Timer.scheduledTimer(timeInterval: 0.003, target: self, selector: #selector("openFrameAnimation"), userInfo: nil, repeats: true)
    
    Run Code Online (Sandbox Code Playgroud)
  2. 停止计时器

        timer.invalidate()
        timer = Timer()
    
    Run Code Online (Sandbox Code Playgroud)