dispatch_after - GCD in Swift?

前端 未结 25 2388
心在旅途
心在旅途 2020-11-21 06:07

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         


        
25条回答
  •  终归单人心
    2020-11-21 06:47

    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.

    Delaying a task with 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."
    }
    

    Notes

    • If you need to cancel the action before it happens, simply call timer.invalidate().
    • For a repeated action use 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.

提交回复
热议问题