dispatch_after - GCD在swift? [英] dispatch_after - GCD in swift?
问题描述
我已经浏览了 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?#>)
推荐答案
A更清楚的结构概念:
A clearer idea of the structure:
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真的很好延迟
功能。
I recommend using @matt's really nice delay
function.
编辑2:
In 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) - > DispatchTime
-
func +(time:DispatchWalltime,interval:DispatchTimeInterval) - > DispatchWalltime
func +(time: DispatchTime, seconds: Double) -> DispatchTime
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 - GCD在swift?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!