dispatch_after - Swift 中的 GCD? [英] dispatch_after - GCD in Swift?

查看:20
本文介绍了dispatch_after - Swift 中的 GCD?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经浏览了 iBook 来自 Apple,找不到它的任何定义:

I've gone through the iBook from Apple, and couldn't find any definition of it:

谁能解释一下dispatch_after的结构?

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

推荐答案

更清晰的结构思路:

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

dispatch_time_t 是一个 UInt64.dispatch_queue_t 实际上是 NSObject 的别名,但是你应该使用你熟悉的 GCD 方法来获取队列.该块是一个 Swift 闭包.具体来说,dispatch_block_t被定义为() ->void,相当于() ->().

dispatch_time_t is a UInt64. The dispatch_queue_t is actually type aliased to an NSObject, but you should just use your familiar GCD methods to get queues. The block is a Swift closure. Specifically, dispatch_block_t is defined as () -> Void, which is equivalent to () -> ().

示例用法:

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

我建议使用 @matt 非常好的 delay函数.

I recommend using @matt's really nice delay function.

编辑 2:

在 Swift 3 中,将有新的 GCD 包装器.请参阅此处:https://github.com/apple/swift-evolution/blob/master/proposals/0088-libdispatch-for-swift3.md

In Swift 3, there will be new wrappers for GCD. See here: https://github.com/apple/swift-evolution/blob/master/proposals/0088-libdispatch-for-swift3.md

原始示例将在 Swift 3 中编写如下:

The original example would be written as follows in Swift 3:

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

请注意,您可以将 deadlineTime 声明写为 DispatchTime.now() + 1.0 并获得相同的结果,因为 + 运算符是重写如下(类似于 -):

Note that you can write the deadlineTime declaration as DispatchTime.now() + 1.0 and get the same result because the + operator is overridden as follows (similarly for -):

  • func +(time: DispatchTime, seconds: Double) ->调度时间
  • func +(time: DispatchWalltime, interval: DispatchTimeInterval) ->DispatchWalltime

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

This means that if you don't use the DispatchTimeInterval enum and just write a number, it is assumed that you are using seconds.

这篇关于dispatch_after - Swift 中的 GCD?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆