在Swift 2中,我能够用以下代码创建队列:
let concurrentQueue = dispatch_queue_create("com.swift3.imageQueue", DISPATCH_QUEUE_CONCURRENT)
但是这不能在Swift 3中编译。
在Swift 3中,首选的方式是什么?
在Swift 2中,我能够用以下代码创建队列:
let concurrentQueue = dispatch_queue_create("com.swift3.imageQueue", DISPATCH_QUEUE_CONCURRENT)
但是这不能在Swift 3中编译。
在Swift 3中,首选的方式是什么?
当前回答
DispatchQueue.main.async(execute: {
// code
})
其他回答
swift 5更新
串行队列
let serialQueue = DispatchQueue.init(label: "serialQueue")
serialQueue.async {
// code to execute
}
并发队列
let concurrentQueue = DispatchQueue.init(label: "concurrentQueue", qos: .background, attributes: .concurrent, autoreleaseFrequency: .inherit, target: nil)
concurrentQueue.async {
// code to execute
}
来自苹果文档:
参数
标签
附加到队列上的字符串标签,以便在诸如Instruments、sample、stackshots和崩溃报告等调试工具中惟一地标识队列。因为应用程序、库和框架都可以创建自己的分派队列,所以建议使用反向dns命名风格(com.example.myqueue)。该参数为可选参数,可以为NULL。
qos
与队列关联的服务质量级别。该值决定了系统调度任务执行的优先级。有关可能值的列表,请参见DispatchQoS.QoSClass。
属性
要与队列关联的属性。包含concurrent属性以创建并发执行任务的调度队列。如果忽略该属性,分派队列将按顺序执行任务。
autoreleaseFrequency
自动释放由队列调度的块创建的对象的频率。有关可能值的列表,请参见dispatchqueue . autoreleasfrequency。
目标
执行块的目标队列。如果希望系统提供适合当前对象的队列,则指定DISPATCH_TARGET_QUEUE_DEFAULT。
由于OP问题已经在上面得到了回答,我只想添加一些速度方面的考虑:
在DispatchQueue.global中为async函数分配的优先级类有很大不同。
我不建议使用.background线程优先级运行任务,尤其是在iPhone X上,因为任务似乎是分配在低功耗内核上的。
下面是一个计算密集型函数的一些真实数据,该函数从XML文件中读取(带缓冲)并执行数据插值:
设备名/ .background / .utility / .default / .userInitiated / .userInteractive
iPhone X: 18.7s / 6.3s / 1.8s / 1.8s iPhone 7: 4.6s / 3.1s / 3.0s / 2.8s / 2.6s iPhone 5s: 7.3s / 6.1s / 4.0s / 4.0s / 3.8s
注意,并不是所有设备的数据集都相同。iPhone X最大,iPhone 5s最小。
在>=Swift 3下编译。这个例子包含了我们需要的大部分语法。
QoS——新的服务质量语法
弱自中断保留周期
如果self不可用,什么都不做
Async全局实用程序队列——用于网络查询,不等待结果,它是一个并发队列,块(通常)在启动时不等待。并发队列的例外可能是,当它的任务限制已经达到时,队列临时变成一个串行队列并等待,直到该队列中的某个先前的任务完成。
async主队列——对于触摸UI,块不等待结果,而是等待它在开始时的槽。主队列是一个串行队列。
当然,你需要添加一些错误检查…
DispatchQueue.global(qos: .utility).async { [weak self] () -> Void in
guard let strongSelf = self else { return }
strongSelf.flickrPhoto.loadLargeImage { loadedFlickrPhoto, error in
if error != nil {
print("error:\(error)")
} else {
DispatchQueue.main.async { () -> Void in
activityIndicator.removeFromSuperview()
strongSelf.imageView.image = strongSelf.flickrPhoto.largeImage
}
}
}
}
Swift 3
DispatchQueue.main.async {
// Write your code here
}
DispatchQueue.main.async(execute: {
// code
})