正在使NSTimer无效



我有一个NSTimer,它设置了150秒,当它降到0时,它应该停止计数并结束我正在创建的游戏。但是,当我调用invalidate()时,它将继续运行。我也有它,这样当计时器无效但没有运气时,它应该打印"计时器停止"。还有别的办法吗?

这是我的代码:

import SpriteKit
var countDown: NSTimer()
class GameScene: SKScene {
  override func didMoveToView(view:SKView)
   countDown = NSTimer.scheduledTimerWithTimeInterval(1.0, target: self, selector: "subtractTime", userInfo: nil, repeats: true)
}
 override func update() {
  if countDown == 0 {
      countDown.invalidate()
       print("Timer stopped")
     }

这是因为比较了countDownInt的值。如果您需要在计时器启动时使其无效,请在subtractTime方法中执行此操作。

您还提到您将计时器设置为150秒。但在代码示例中,它是1.0。所以我建议你希望你的选择器被调用150次,延迟一秒。如果是这样,您可以简单地添加计数器变量:

var counter = 0
...
func subtractTime() {
  counter += 1
  if counter == 150 {
    countDown.invalidate()
    countDown = nil // also add this line to escape retain cycle
    return
  }
  ...
}

最新更新