Search code examples
functionswiftnstimer

Swift NSTimer only runs function once


So I have looked around, and I can't find what I am doing wrong, I am running Swift 1.2, and using SpriteKit by the way.

//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)   
        }  
    }

I want my function countdown to run 4 times, but It is only running once for some reason, even though its set to run forever, I am also not getting any error or warnings, sorry if obvious, and if code is hard to understand, I just included the function it was all in.


Solution

  • 'Selector(countdown())' is evaluated to nil. So,

    1.Move 'countdown' function to outside of touchesBegin.

    2.Use 'selector: "countdown"' instead of 'Selector(countdown())'

    3.Invalidate your timer after called four times.

    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)
    }