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

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)

i use a similar approach to Luke. Only a caveat for people who are "private methods" purists:

DO NOT make callback private in Swift.

If You write:

private func timerCallBack(timer: NSTimer){

..

you will get:

timerCallBack:]: unrecognized selector sent to instance... Terminating app due to uncaught exception 'NSInvalidArgumentException'


NSTimer's are not scheduled automatically unless you use NSTimer.scheduledTimerWithTimeInterval:

myTimer = NSTimer.scheduledTimerWithTimeInterval(5.0, target: self, selector: "timerFunc", userInfo: nil, repeats: true)

As Drewag and Ryan pointed out, you need to create a scheduled timer (or schedule it yourself) It's easiest to create it scheduled already with:

myTimer = NSTimer.scheduledTimerWithTimeInterval(5.0, target: self, selector: "timerFunc:", userInfo: nil, repeats: true)

You also need to change your definition of timerFunc (and the associated selector) to take an argument and end with a ':'

func timerFunc(timer:NSTimer!) {
    ...
}