使NSTimer无效

Rae*_*ker 2 nstimer sprite-kit swift

我有一个设置为150秒的NSTimer,当它降到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")
     }
Run Code Online (Sandbox Code Playgroud)

rky*_*kyr 7

这是因为你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
  }
  ...
}
Run Code Online (Sandbox Code Playgroud)