NSTimers swift 不触发

NSTimers swift don't fire

我有 3 个 NSTimers:

var timer = NSTimer()
var scoreTimer = NSTimer()
var gameTmer = NSTimer()

然后在 "viewDidLoad":

var sel = Selector("testFunc:")

timer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: sel, userInfo: nil, repeats: true)

scoreTimer = NSTimer.scheduledTimerWithTimeInterval(0.1, target: self, selector: sel, userInfo: nil, repeats: true)

gameTmer = NSTimer.scheduledTimerWithTimeInterval(0.1, target: self, selector: sel, userInfo: nil, repeats: true)

testFunc 就是这样:

func testFunc(timer : NSTimer){
    println("working")
}

但它们不起作用。如果我尝试使用 "fire()",那么他们会调用 testFunc,但其他方式 - 不。

我找到了解决方案:

您可以为每个计时器删除 .scheduledTimerWithTimeInterval 并添加 NSRunLoop.mainRunLoop().addTimer(timer, forMode: NSRunLoopCommonModes)。因此,您的代码将如下所示:

var sel = Selector("testFunc:")

timer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: sel, userInfo: nil, repeats: true)

scoreTimer = NSTimer.scheduledTimerWithTimeInterval(0.1, target: self, selector: sel, userInfo: nil, repeats: true)

gameTmer = NSTimer.scheduledTimerWithTimeInterval(0.1, target: self, selector: sel, userInfo: nil, repeats: true)

NSRunLoop.mainRunLoop().addTimer(timer, forMode: NSRunLoopCommonModes)

NSRunLoop.mainRunLoop().addTimer(scoreTimer, forMode: NSRunLoopCommonModes)

NSRunLoop.mainRunLoop().addTimer(gameTmer, forMode: NSRunLoopCommonModes)