I\'ve gone through the iBook from Apple, and couldn\'t find any definition of it:
Can someone explain the structure of dispatch_after
?
d
Although not the original question by the OP, certain NSTimer
related questions have been marked as duplicates of this question, so it is worth including an NSTimer
answer here.
NSTimer
vs dispatch_after
NSTimer
is more high level while dispatch_after
is more low level.NSTimer
is easier to cancel. Canceling dispatch_after
requires writing more code.NSTimer
Create an NSTimer
instance.
var timer = NSTimer()
Start the timer with the delay that you need.
// invalidate the timer if there is any chance that it could have been called before
timer.invalidate()
// delay of 2 seconds
timer = NSTimer.scheduledTimerWithTimeInterval(2.0, target: self, selector: #selector(delayedAction), userInfo: nil, repeats: false)
Add a function to be called after the delay (using whatever name you used for the selector
parameter above).
func delayedAction() {
print("Delayed action has now started."
}
timer.invalidate()
.repeats: true
. If you have a one time event with no need to cancel then there is no need to create the timer
instance variable. The following will suffice:
NSTimer.scheduledTimerWithTimeInterval(2.0, target: self, selector: #selector(delayedAction), userInfo: nil, repeats: false)
See my fuller answer here.