Using NSTimer in a Fast Playground

I would like to know how to use NSTimer inside Swift Playground. This question has been asked before , but none of the answers actually answered the question.

Here is my pad code:

 import Foundation class MyClass { func startTimer() { NSTimer.scheduledTimerWithTimeInterval(0.5, target: self, selector: "onTimer:", userInfo: nil, repeats: true) } func onTimer(timer:NSTimer!) { println("Timer here") } } var anInstance = MyClass() anInstance.startTimer() 

Running NSTimer with scheduledTimerWithTimeInterval creates a timer and that schedules it in the current run loop.

But the onTimer method onTimer never called. What for?

+4
source share
1 answer

First of all, your onTimer method must be declared as @objc , or NSTimer cannot find it.

As for your question, this is because you did not start a run loop.

For this, CFRunLoopRun() is the simplest solution I think.

 import Foundation class MyClass { func startTimer() { NSTimer.scheduledTimerWithTimeInterval(0.5, target: self, selector: "onTimer:", userInfo: nil, repeats: true) } @objc func onTimer(timer:NSTimer!) { println("Timer here") } } var anInstance = MyClass() anInstance.startTimer() CFRunLoopRun() // <-- HERE! 

For completeness, like @MartinR seen in a comment, you can also use XCPSetExecutionShouldContinueIndefinitely()

 import Foundation import XCPlayground XCPSetExecutionShouldContinueIndefinitely() class MyClass { func startTimer() { NSTimer.scheduledTimerWithTimeInterval(0.5, target: self, selector: "onTimer:", userInfo: nil, repeats: true) } @objc func onTimer(timer:NSTimer!) { println("Timer here") } } var anInstance = MyClass() anInstance.startTimer() 

In this case, the playground only starts the seconds indicated on the timeline:

screenshot

+12
source

Source: https://habr.com/ru/post/1258229/


All Articles