1

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")
    }
bhzag
  • 2,932
  • 7
  • 23
  • 39

3 Answers3

12

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:.

Chuck
  • 234,037
  • 30
  • 302
  • 389
  • It tried using the first option you stated and it didn't fire either. – bhzag Jun 18 '14 at 20:02
  • @user: Is this in an environment where a run loop is running? – Chuck Jun 18 '14 at 20:05
  • How do I tell if a run loop is running? – bhzag Jun 18 '14 at 20:13
  • 1
    @user3746375: If it's a normal AppKit or UIKit app with a functioning interface that doesn't have any alerts or menus open, it probably has a running run loop. If that isn't the case and you don't know if you have one, you probably don't. – Chuck Jun 18 '14 at 20:17
  • To add a timer to a run loop: Swift 3: `RunLoop.current.add(myTimer, forMode: RunLoopMode.commonModes)` – twodayslate Mar 06 '17 at 17:57
4

You can use this code for your NSTimer:

Swift 2

func timer() {
   var timer = NSTimer.scheduledTimerWithTimeInterval(2.0, target: self, selector: "timerFunc", userInfo: nil, repeats: false)
}
func timerFunc() {
   println("it worked")
}

Swift 3, 4, 5

func timer() {
    var timer = Timer.scheduledTimer(timeInterval: 2.0, target: self, selector: #selector(timerFunc), userInfo: nil, repeats: false)
}
@objc func timerFunc() {
    print("it worked")
}

You have to use the scheduledTimerWithTimeInterval:target:selector:userInfo:repeats: class method to run your timer.

Hope this can help you.

Karen Hovhannisyan
  • 1,140
  • 2
  • 21
  • 31
Bigfoot11
  • 911
  • 2
  • 11
  • 25
0

you create the Selector like below.

let @Selector : Selector = "timerFireMethod:"

and then create the timer

var timer = NSTimer.scheduledTimerWithTimeInterval(1.0, 
                target: self, 
                selector: @Selector,
                userInfo: userInfo, 
                repeats: true)
Daxesh Nagar
  • 1,405
  • 14
  • 22