Search code examples
iosswiftnstimer

Trouble with NSTimer in Swift


I tried this but nothing happened. Is there something wrong with the selector?

    func timer() {
       var timer = NSTimer(timeInterval: 2.0, target: self, selector:Selector("function"), userInfo: nil, repeats: false)
    }
    func function() {
       println("it worked")
    }

Solution

  • You're just creating the timer, but not adding it to the run loop. You'll either need to use the equivalent scheduledTimerWithTimeInterval:target:selector:userInfo:repeats: class method or schedule it on the run loop with addTimer:forMode:.