swift - dispatch_after 时间立即触发

标签 swift grand-central-dispatch

这是我第一次使用 GCD,我承认,如果我犯了傻,我深表歉意。我有一个 dispatch_after 命令,它对我来说是一个方便的延迟。

我的问题是当我发送

dispatch_after(500000000000, dispatch_get_main_queue()){
    println("triggered") //or any other code
}

关闭立即触发(例如,我已经测试过这个并立即“触发”打印)。应该需要更长时间吧?大概多 500 秒。

谢谢:)

最佳答案

dispatch_after(_:_:_:)的第一个参数不是延时,而是时间点。来自 the docs :

when: The temporal milestone returned by dispatch_time or dispatch_walltime.

Discussion This function waits until the specified time and then asynchronously adds block to the specified queue.

你需要构造一个相对于当前时间的延迟,使用dispatch_time(_:_:):

let delayTime = dispatch_time(DISPATCH_TIME_NOW, Int64(500 * NSEC_PER_SEC))
dispatch_after(delayTime, dispatch_get_main_queue()) { ... }

关于swift - dispatch_after 时间立即触发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31949034/

相关文章:

ios - Swift 将数组数组映射到元组数组 - 'map' 生成 [T],而不是预期的

swift - 单元格中的 TextView 具有自动大小

ios - 如何通过协调器模式将值从第二个 View Controller 传递到第一个 View Controller

ios - Swift UISwipeGestureRecognizer 如何检测对角线滑动?

ios - 异步创建包含图像的数组

cocoa-touch - 主要的 Grand Central Dispatch 队列是串行的还是并发的?

ios - 如何阻止 GCD 调度 _after block 返回结果。可能很愚蠢

ios - sleep() 适用于 iOS 但不适用于 mac?

ios - 从服务器获取数据时如何使用typealias

swift - 不可点击的单元格,wen 动画打开