Creating a Timer

suggest change

This will create a timer to call the doSomething method on self in 5 seconds.

Swift

let timer = NSTimer.scheduledTimerWithTimeInterval(5,
                               target: self,
                             selector: Selector("doSomething"),
                             userInfo: nil,
                              repeats: false)

Selector("doSomething") does not call the method. Selector(doSomething()) would call it immediately and pass the result into Selector.

Swift 3

let timer = Timer.scheduledTimer(timeInterval: 5,
                                       target: self,
                                     selector: #selector(doSomething),
                                     userInfo: nil,
                                      repeats: false)

doSomething must be visible to Objective-C (@objc). The run loop that creates the timer must be running. A timer created on the main thread fires on the main thread.

Objective-C

NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:5.0 target:self selector:@selector(doSomething) userInfo:nil repeats:NO];

Setting repeats to false/NO indicates that we want the timer to fire only once. If we set this to true/YES, it would fire every five seconds until manually invalidated.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents