Search code examples
swiftnstimer

Using an NSTimer in Swift


In this scenario, timerFunc() is never called. What am I missing?

class AppDelegate: NSObject, NSApplicationDelegate {

    var myTimer: NSTimer? = nil

    func timerFunc() {
        println("timerFunc()")
    }

    func applicationDidFinishLaunching(aNotification: NSNotification?) {
        myTimer = NSTimer(timeInterval: 5.0, target: self, selector:"timerFunc", userInfo: nil, repeats: true)
    }
}

Solution

  • You can create a scheduled timer which automatically adds itself to the runloop and starts firing:

    Swift 2

    NSTimer.scheduledTimerWithTimeInterval(0.5, target: self, selector: "timerDidFire:", userInfo: userInfo, repeats: true)
    

    Swift 3, 4, 5

    Timer.scheduledTimer(withTimeInterval: 0.5, target: self, selector: #selector(timerDidFire(_:)), userInfo: userInfo, repeats: true)
    

    Or, you can keep your current code, and add the timer to the runloop when you're ready for it:

    Swift 2

    let myTimer = NSTimer(timeInterval: 0.5, target: self, selector: "timerDidFire:", userInfo: nil, repeats: true)
    NSRunLoop.currentRunLoop().addTimer(myTimer, forMode: NSRunLoopCommonModes)
    

    Swift 3, 4, 5

    let myTimer = Timer(timeInterval: 0.5, target: self, selector: #selector(timerDidFire(_:)), userInfo: nil, repeats: true)
    RunLoop.current.add(myTimer, forMode: RunLoop.Mode.common)