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

      

+3


source to share


1 answer


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

+1


source







All Articles