I tried
var timer = NSTimer()
timer(timeInterval: 0.01, target: self, selector: update, userInfo: nil, repeats: false)
But, I got an error saying
'(timeInterval: $T1, target: ViewController, selector: () -> (), userInfo: NilType, repeats: Bool) -> $T6' is not identical to 'NSTimer'
Check with:
for swift 3 and Xcode 8.2 (nice to have blocks, but if You compile for iOS9 AND want userInfo):
...
Repeated event
You can use a timer to do an action multiple times, as seen in the following example. The timer calls a method to update a label every half second.
Here is the code for that:
Delayed event
You can also use a timer to schedule a one time event for some time in the future. The main difference from the above example is that you use
repeats: false
instead oftrue
.The above example calls a method named
delayedAction
two seconds after the timer is set. It is not repeated, but you can still calltimer.invalidate()
if you need to cancel the event before it ever happens.Notes
Related
Swift 3, pre iOS 10
Swift 3, iOS 10+
Notes
@objc
And Create Fun By The Name createEnemy
As of iOS 10 there is also a new block based Timer factory method which is cleaner than using the selector: