首先,你的onTimer
方法必须声明为@objc
, or NSTimer
找不到那个。
至于你的问题,是因为你还没有启动runloop。
要做到这一点,CFRunLoopRun()
是我认为最简单的解决方案。
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!
为了完整起见,正如@MartinR 在评论中提到的,您还可以使用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()
在这种情况下,Playground 仅运行时间轴中指定的秒数: