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)
}
}
With swift3, you can run it with,
You can create a scheduled timer which automatically adds itself to the runloop and starts firing:
Or, you can keep your current code, and add the timer to the runloop when you're ready for it:
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:
You also need to change your definition of timerFunc (and the associated selector) to take an argument and end with a ':'
NSTimer's are not scheduled automatically unless you use
NSTimer.scheduledTimerWithTimeInterval
:Since this thread made me try to put the timer on a RunLoop myself (which solved my problem), I post my specific case as well - who knows maybe it helps somebody. My timer is created during app start up and initialisation of all the objects. My problem was that, while it did schedule the timer, it still never fired. My guess is, this was the case because
scheduledTimerWithTimeInterval
was putting the timer on a different RunLoop during startup of the App. If I just initialise the timer and then useNSRunLoop.mainRunLoop().addTimer(myTimer, forMode:NSDefaultRunLoopMode)
instead, it works fine.To do it with the method the OP suggests, you need to add it to a run loop:
The documentation also says that the target should take an argument, but it works without it.