在这种情况下,永远不会调用timerFunc()。我想念什么?
class AppDelegate: NSObject, NSApplicationDelegate { var myTimer: NSTimer? = nil func timerFunc() { println("timerFunc()") } func applicationDidFinishLaunching(aNotification: NSNotification?) { myTimer = NSTimer(timeInterval: 5.0, target: self, selector:"timerFunc", userInfo: nil, repeats: true) } }
您可以创建一个计划的计时器,该计时器自动将其自身添加到运行循环并开始触发:
迅捷2
NSTimer.scheduledTimerWithTimeInterval(0.5, target: self, selector: "timerDidFire:", userInfo: userInfo, repeats: true)
斯威夫特3,4,5
Timer.scheduledTimer(withTimeInterval: 0.5, target: self, selector: #selector(timerDidFire(_:)), userInfo: userInfo, repeats: true)
或者,您可以保留当前代码,并在准备就绪时将计时器添加到runloop中:
let myTimer = NSTimer(timeInterval: 0.5, target: self, selector: "timerDidFire:", userInfo: nil, repeats: true) NSRunLoop.currentRunLoop().addTimer(myTimer, forMode: NSRunLoopCommonModes)
let myTimer = Timer(timeInterval: 0.5, target: self, selector: #selector(timerDidFire(_:)), userInfo: nil, repeats: true) RunLoop.current.add(myTimer, forMode: RunLoop.Mode.common)