Tried this in the playground, but "timer" isn't ever printed. Why isn't the timer firing?
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()
I then tried to have Tester subclass NSObject and got the same results. "initialized" prints, but not "timer". No errors produced either.
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()
This is peculiar: it appears that, to be able to set an NSTimer, the runloop has to be running so that you can call this:
let mainLoop = NSRunLoop.mainRunLoop()
mainLoop.addTimer(test.myTimer!, forMode: NSDefaultRunLoopMode)
Adding the timer to the runloop is what allows it to call timerFunc. However, the NSRunLoop does not run in a Playground (the main loops stops after it runs your current code), so you can't use an NSTimer like this there (you'd have to use it within a project).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With