iosswiftnstimer

Simple NSTimer implementation issue


I have just started to learn swift 2 and I am testing a few things in an Xcode 'playground'. When a create an instance of the 'pyx' (below) I am not seeing the console output I would expect. I am sure I have made a silly mistake but after staring at it for a while I cannot figure it out.

class zxy {
    
    var gameTimer = NSTimer()
    var counter = 0

    
    init() {
            gameTimer = NSTimer (timeInterval: 1, target: self, selector: "Run:", userInfo: nil, repeats: true)
    }
    
    
    func Run(timer : NSTimer) {
        
        while(counter < 10){
            print(counter)
            counter++
        }
        
        timer.invalidate()
    }
    
}

Solution

  • You have 2 problems with your code. As @glenstorey points out in his answer, you need to call the method scheduledTimerWithTimeInterval:target:selector:userInfo:repeats:, not the init method you're calling.

    EDIT:

    As @DanBeauleu says in his comment to my answer, the call would look like this in Swift:

    NSTimer.scheduledTimerWithTimeInterval(
      1, 
      target: self, 
      selector: "Run:", 
      userInfo: nil, 
      repeats: true) 
    

    The second problem is your Run method.

    You don't want a while loop. That will repeat 10 times in a tiny fraction of a second the first time the timer fires, then invalidate the timer.

    Your timer method needs to be changed like this:

    func Run(timer : NSTimer) 
    {
    
      if counter < 10
      {
        print(counter)
        counter++
      }
      else
      {
        timer.invalidate()
      }
    }
    

    (BTW, by strong convention, method/function names should start with a lower-case letter, so your Run function should be named run instead.)