我翻遍了苹果的iBook,找不到任何关于它的定义:

有人能解释一下dispatch_after的结构吗?

dispatch_after(<#when: dispatch_time_t#>, <#queue: dispatch_queue_t?#>, <#block: dispatch_block_t?#>)

当前回答

这对我很管用。

斯威夫特3:

let time1 = 8.23
let time2 = 3.42

// Delay 2 seconds

DispatchQueue.main.asyncAfter(deadline: .now() + 2.0) {
    print("Sum of times: \(time1 + time2)")
}

objective - c:

CGFloat time1 = 3.49;
CGFloat time2 = 8.13;

// Delay 2 seconds

dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
    CGFloat newTime = time1 + time2;
    NSLog(@"New time: %f", newTime);
});

其他回答

我经常使用dispatch_after,所以我写了一个顶级实用函数来简化语法:

func delay(delay:Double, closure:()->()) {
    dispatch_after(
        dispatch_time(
            DISPATCH_TIME_NOW,
            Int64(delay * Double(NSEC_PER_SEC))
        ),
        dispatch_get_main_queue(), closure)
}

现在你可以这样说:

delay(0.4) {
    // do stuff
}

哇,一种你可以改进的语言。还有什么比这更好的呢?


更新Swift 3, Xcode 8种子6

看起来几乎不值得费心,现在他们已经改进了调用语法:

func delay(_ delay:Double, closure:@escaping ()->()) {
    let when = DispatchTime.now() + delay
    DispatchQueue.main.asyncAfter(deadline: when, execute: closure)
}

保留当前队列!

除了很好地回答这个问题之外,您还可以考虑保留当前队列以防止不必要的主队列操作(例如,当您试图延迟一些异步操作时)。

func after(_ delay: TimeInterval,
           perform block: @escaping ()->(),
           on queue: DispatchQueue = OperationQueue.current?.underlyingQueue ?? .main) { // So this `queue` preserves the current queue and defaulted to the `main`. Also the caller can pass in the desired queue explicitly
    queue.asyncAfter(deadline: .now() + delay, execute: block)
}

用法:

after(3) {
    // will be executed on the caller's queue
    print(Date())
}

虽然不是OP的原始问题,但某些与NSTimer相关的问题已被标记为该问题的重复,因此值得在这里包含NSTimer的答案。

NSTimer vs dispatch_after

NSTimer更高级,而dispatch_after更低级。 NSTimer更容易取消。取消dispatch_after需要编写更多的代码。

用NSTimer延迟任务

创建一个NSTimer实例。

var timer = NSTimer()

以您需要的延迟启动计时器。

// 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) 

添加一个在延迟之后被调用的函数(使用您用于上面选择器参数的任何名称)。

func delayedAction() {
    print("Delayed action has now started."
}

笔记

如果需要在操作发生之前取消该操作,只需调用timer.invalidate()。 对于重复的动作使用repeats: true。 如果你有一个不需要取消的一次性事件,那么就不需要创建计时器实例变量。以下内容就足够了: NSTimer.scheduledTimerWithTimeInterval(2.0, target: self, selector: #selector(delayedAction), userInfo: nil, repeats: false) 在这里看到我更完整的回答。

Swift 4有一个很短的方法来做到这一点:

Timer.scheduledTimer(withTimeInterval: 2, repeats: false) { (timer) in
    // Your stuff here
    print("hello")
}

更清晰的结构概念:

dispatch_after(when: dispatch_time_t, queue: dispatch_queue_t, block: dispatch_block_t?)

dispatch_time_t为UInt64。dispatch_queue_t实际上是一个NSObject的类型别名,但是你应该使用你熟悉的GCD方法来获取队列。该区块是一个快速关闭。具体来说,dispatch_block_t定义为()-> Void,相当于()->()。

使用示例:

let delayTime = dispatch_time(DISPATCH_TIME_NOW, Int64(1 * Double(NSEC_PER_SEC)))
dispatch_after(delayTime, dispatch_get_main_queue()) {
    print("test")
}

编辑:

我推荐使用@matt的延时函数。

编辑2:

在Swift 3中,GCD将会有新的包装器。请看这里:https://github.com/apple/swift-evolution/blob/master/proposals/0088-libdispatch-for-swift3.md

原来的例子在Swift 3中是这样写的:

let deadlineTime = DispatchTime.now() + .seconds(1)
DispatchQueue.main.asyncAfter(deadline: deadlineTime) {
    print("test")
}

注意,你可以将deadlineTime声明写为DispatchTime.now() + 1.0,并得到相同的结果,因为+操作符被重写如下(与-类似):

func +(time: DispatchTime, seconds: Double) -> DispatchTime . func +(time: DispatchTime, seconds: Double func +(time: DispatchWalltime, interval: DispatchTimeInterval) -> DispatchWalltime . func +(time: DispatchWalltime, interval: DispatchTimeInterval

这意味着如果您不使用DispatchTimeInterval enum,而只是写一个数字,则假定您使用的是秒。