Swift3.0中GCD延时函数asyncAfter的使用

2016-12-05 10:24

尝试了下Swift3.0中GCD的延时函数,发现貌似与之前的有挺大的不同,折腾了好一会终于算是会用了一丢丢

  • swift3.0中有4个延迟函数,如下
public func asyncAfter(deadline: DispatchTime, qos: DispatchQoS = default, flags: DispatchWorkItemFlags = default, execute work: @escaping @convention(block) () -> Swift.Void)

public func asyncAfter(wallDeadline: DispatchWallTime, qos: DispatchQoS = default, flags: DispatchWorkItemFlags = default, execute work: @escaping @convention(block) () -> Swift.Void)

public func asyncAfter(deadline: DispatchTime, execute: DispatchWorkItem)

public func asyncAfter(wallDeadline: DispatchWallTime, execute: DispatchWorkItem)

一般开发中,用第三个应该就足够了,下面看看具体使用

public func asyncAfter(deadline: DispatchTime, execute: DispatchWorkItem)
// 该方法接收一个DispatchTime的参数,点进这个类型的里面可以发现实个结构体
public struct DispatchTime : Comparable {
    public let rawValue: dispatch_time_t
    public static func now() -> DispatchTime
    public static let distantFuture: DispatchTime
    public init(uptimeNanoseconds: UInt64)
    public var uptimeNanoseconds: UInt64 { get }
}
// 看了之后一片迷茫,不知道怎么使用,最后做了个大胆的尝试
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 2, execute: {
            self.tableView?.reloadData()
            if self.refreshControl?.isRefreshing == true {
                self.refreshControl?.endRefreshing()
            }
        })

DispatchTime.now() 获取当前时间,
DispatchTime.now() + 2, 在当前时间的基础上加2,那就是延时两秒了

以上仅供参考,如有不对的地方,还望各位指教原文链接