NSTimer not stopping when invalidated in this function

半腔热情 提交于 2019-12-07 22:26:14

问题


I'm trying to use NTTimer but it doesn't work.

It is started here:

timer = NSTimer.scheduledTimerWithTimeInterval(0.003, target: self, selector: "openFrameAnimation", userInfo: nil, repeats: true)

It fires this function:

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
}

Even if "STOP" is printed over and over again, the timer continues to call openFrameAnimation and I can't stop it. How can I stop timer when condition is verified?

Log:

[...]
*Animation Goes...  1456613095.27813
STOP
[...]
Animation Goes...  1456613095.51233
STOP
Animation Goes...  1456613095.54458
[...]
STOP
Animation Goes...  1456613095.5938
STOP*

回答1:


Swift 4

  1. add

    var timer = Timer()
    

to the top of the class

  1. set your timer (using your original info - you may want to change as per some suggestions, particularly the one from @Rob about the frame rate)

    timer = Timer.scheduledTimer(timeInterval: 0.003, target: self, selector: #selector("openFrameAnimation"), userInfo: nil, repeats: true)
    
  2. stop the timer

        timer.invalidate()
        timer = Timer()
    


来源:https://stackoverflow.com/questions/35676407/nstimer-not-stopping-when-invalidated-in-this-function

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!