NSTimer not stopping when invalidated in this func

2019-05-29 09:01发布

问题:

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()
    


标签: swift nstimer