3

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()
Aaron Bratcher
  • 6,051
  • 2
  • 39
  • 70
  • possible duplicate of [How do I run Asynchronous callbacks in Playground](http://stackoverflow.com/questions/24058336/how-do-i-run-asynchronous-callbacks-in-playground) – rickster Sep 07 '14 at 01:11
  • 1
    because the runloop isn't running in the playground. Gotcha. – Aaron Bratcher Sep 07 '14 at 01:18

1 Answers1

1

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

AstroCB
  • 12,337
  • 20
  • 57
  • 73
  • Calling it is the point of the timer. It should be calling it about once a second. – Aaron Bratcher Sep 07 '14 at 00:43
  • @AaronBratcher True. I've looked into this a bit and it's weird. You've probably already found the answer from rickster's auto-duplicate comment, but I've edited my answer to reflect the changes. There are some ways around it (`import XCPlayground` and run `XCPSetExecutionShouldContinueIndefinitely()`), but they don't always work as expected. – AstroCB Sep 07 '14 at 01:42