GCD 差异 Swift 3

GCD differences in Swift 3

当我注意到 Swift 3 更改了它的语法时,我正在研究 Grand Central Dispatch

所以,是这样的:

let queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)

    dispatch_async(queue) { () -> Void in

        let img1 = Downloader.downloadImageWithURL(imageURLs[0])

        dispatch_async(dispatch_get_main_queue(), {

            self.imageView1.image = img1
        })   
    }

和这个有什么不同吗?

DispatchQueue.global(qos: .default).async { [weak self]

            () -> Void in

            let img1 = Downloader.downloadImageWithURL(imageURLs[0])

            DispatchQueue.main.async {

                ()->Void in

                self?.imageView1.image = img1
            }

        }

我是否应该创建一个变量来包含 DispatchQueue.global(qos: .default).async

除了在第一种方法中没有弱化 self 之外,两种调用是等价的。

是否创建变量取决于您的(方便)偏好,技术上没有区别。

Swift 3 对 Grand Central Dispatch 语法和用法进行了许多改进。

以前,我们会选择调度方法(同步与异步),然后选择我们要将任务调度到的队列。更新后的 GCD 颠倒了这个顺序——我们首先选择队列,然后应用调度方法。

DispatchQueue.global(attributes: [.qosDefault]).async { 
    // Background thread
    DispatchQueue.main.async(execute: { 
        // UI Updates
    })
}

队列属性

您会注意到队列现在在 init 上具有属性。这是一个 Swift 选项集,可以包括队列选项,例如串行与并发、内存和 activity 管理选项以及服务质量(.default、.userInteractive、.userInitiated、.utility 和 .background) . 服务质量取代了 iOS8 中弃用的旧优先级属性。如果您习惯了优先级队列,下面是它们如何映射到 QOS 个案例:

* DISPATCH_QUEUE_PRIORITY_HIGH:         .userInitiated
* DISPATCH_QUEUE_PRIORITY_DEFAULT:      .default
* DISPATCH_QUEUE_PRIORITY_LOW:          .utility
* DISPATCH_QUEUE_PRIORITY_BACKGROUND:   .background

工作项

队列不是 GCD 中获得 Swift OptionSet 的唯一部分。工作项也有更新的 Swift 语法:

let workItem = DispatchWorkItem(qos: .userInitiated, flags: .assignCurrentContext) {
    // Do stuff
}
queue.async(execute: workItem)

工作项现在可以在 init 上声明质量或服务 and/or 标志。这两个都是可选的,会影响工作项的执行。

dispatch_once

dispatch_once 对于初始化代码和其他只执行一次的函数非常有用。 在 Swift 3 中,dispatch_once 已弃用,应替换为全局或静态变量和常量。

// Examples of dispatch_once replacements with global or static constants and variables. 
// In all three, the initialiser is called only once. 

// Static properties (useful for singletons).
class Object {
    static let sharedInstance = Object()
}

// Global constant.
let constant = Object()

// Global variable.
var variable: Object = {
    let variable = Object()
    variable.doSomething()
    return variable
}()

dispatch_assert

今年 Apple OS 版本中的另一个新功能是发货先决条件。这些替换 dispatch_assert 并允许您在执行代码之前检查您是否在预期的线程上。这对于更新 UI 并且必须在主队列上执行的函数特别有用。这是一个简单的例子:

let queue = DispatchQueue.global(attributes: .qosUserInitiated)
let mainQueue = DispatchQueue.main

mainQueue.async {
    dispatchPrecondition(condition: .notOnQueue(mainQueue))
    // This code won't execute
}

queue.async {
    dispatchPrecondition(condition: .onQueue(queue))
    // This code will execute
}

来源:https://medium.com/swift-and-ios-writing/a-quick-look-at-gcd-and-swift-3-732bef6e1838#.7hdtfwxb4