Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why isn't this timer firing?

Tags:

swift

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()
like image 235
Aaron Bratcher Avatar asked Dec 05 '25 02:12

Aaron Bratcher


1 Answers

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

like image 172
AstroCB Avatar answered Dec 06 '25 17:12

AstroCB