dispatch_after - GCD in Swift?

前端 未结 25 2390
心在旅途
心在旅途 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:41

    Swift 3+

    This is super-easy and elegant in Swift 3+:

    DispatchQueue.main.asyncAfter(deadline: .now() + 4.5) {
        // ...
    }
    

    Older Answer:

    To expand on Cezary's answer, which will execute after 1 nanosecond, I had to do the following to execute after 4 and a half seconds.

    let delay = 4.5 * Double(NSEC_PER_SEC)
    let time = dispatch_time(DISPATCH_TIME_NOW, Int64(delay))
    dispatch_after(time, dispatch_get_main_queue(), block)
    

    Edit: I discovered that my original code was slightly wrong. Implicit typing causes a compile error if you don't cast NSEC_PER_SEC to a Double.

    If anyone can suggest a more optimal solution I'd be keen to hear it.

提交回复
热议问题