2015-05-04 150 views
-2

所以我看了看周圍,我找不到我做錯了什麼,我正在運行Swift 1.2,並且順便使用了SpriteKit。Swift NSTimer只運行一次功能

//showing you just in case 
import SpriteKit 

//My variables 
var countDownLabel = SKLabelNode(fontNamed: "AmericanTypewriter-Light") 
var time = 4 
var timer = NSTimer() 

//Don't want to give you my entire project, I know I can't override a function outside of its class 
override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) { 
    for touch in (touches as! Set<UITouch>) { 
     let location = touch.locationInNode(self) 

     if playButton.containsPoint(location) { 

//I want this to run 4 times, but is only running once 
      func countdown() { 
       time-- 
        countDownLabel.text = "\(time)" 
      }  

//This is set to run my function every second for ever. 
     timer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: Selector(countdown()), userInfo: nil, repeats: true) 

      playButton.removeFromParent() 

      countDownLabel.fontColor = SKColor.blackColor() 
      countDownLabel.fontSize = 70 
      self.addChild(countDownLabel) 
     } 
    } 

我想我的功能倒計時運行的4倍,但它只是出於某種原因運行一次,即使其設置爲一直運行下去,我還沒有得到任何錯誤或警告,對不起,如果明顯,如果代碼很難理解,我只包含它所有的功能。

+1

其實定時器是_never_運行。創建定時器的代碼部分永遠不會被執行。如果它被執行。定時器將運行,並且您的應用程序會因爲其選擇器無效而崩潰。 – matt

+0

是的,這就是爲什麼我改變它,現在有道理,我不是很確定,找不到它,所以我改變它告訴我停止了錯誤。 –

回答

0

'Selector(countdown())'被評估爲零。所以,

1.移動'倒計時'功能touchesBegin之外。

2.使用 '選擇: 「倒計時」' 而不是 '選擇(倒計時())'

3.Invalidate你的計時器後調用四次。

var time = 4 
var timer = NSTimer() 

func countdown() { 
    if --time == 0 { timer.invalidate() } 
    println("\(time)") 
}  

func X() { 
    timer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: "countdown", userInfo: nil, repeats: true) 
}