swift - NSTimers swift 不会开火

标签 swift nstimer

我有 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)

关于swift - NSTimers swift 不会开火,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27855291/

相关文章:

cocoa - 如果不需要使其失效,是否有任何理由保留预定的 NSTimer?

ios - 添加 scheduledTimerWithTimeInterval 时,NSTimer 不触发选择器

ios - 每 5 秒保存一次

ios - 尝试为 cellForRowAtIndexPath 重用计时器

arrays - 按日期对运行对象数组进行排序(核心数据)

ios - 在 iOS 上,我的应用程序如何获取手机在后台时收到的通知数据?

ios - Swift 2.0 迁移代码错误

ios - 形状,多边形,不会 swift 显示在 GoogleMaps 上

Swift - 使用多个条件对对象数组进行排序

ios - NSTimer 和 NSDateFormatter 麻烦。我的 timerLabel 刷新后消失了吗?