Why doesn't this timer fire?
Tried this on a playground but the "timer" never printed. Why is the timer not working?
class Tester {
var myTimer:NSTimer?
init() {
print("initialized")
myTimer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: "timerFunc:", userInfo: nil, repeats: true)
}
func timerFunc(timer:NSTimer) {
print("timer")
}
}
var test = Tester()
Then I tried to subclass NSObject Tester and got the same results. "initialized" fingerprints, but not "timer". There were no mistakes.
class Tester:NSObject {
var myTimer:NSTimer?
override init() {
super.init()
print("initialized")
myTimer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: "timerFunc:", userInfo: nil, repeats: true)
}
func timerFunc(timer:NSTimer) {
print("timer")
}
}
var test = Tester()
source to share
It's kind of peculiar: it seems that to be able to install NSTimer
, runloop must be running so you can call this:
let mainLoop = NSRunLoop.mainRunLoop()
mainLoop.addTimer(test.myTimer!, forMode: NSDefaultRunLoopMode)
Adding a timer to runloop is what allows it to be called timerFunc
. However, NSRunLoop
does not start in playground (main loops stop after running your current code), so you cannot use NSTimer
like this there (you will need to use it in project).
source to share