ios 如何在 Swift 3 中创建调度队列
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/37805885/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to create dispatch queue in Swift 3
提问by Anish Parajuli ?
In Swift 2, I was able to create queue with the following code:
在 Swift 2 中,我能够使用以下代码创建队列:
let concurrentQueue = dispatch_queue_create("com.swift3.imageQueue", DISPATCH_QUEUE_CONCURRENT)
But this doesn't compile in Swift 3.
但这不能在 Swift 3 中编译。
What is the preferred way to write this in Swift 3?
在 Swift 3 中编写它的首选方法是什么?
回答by Anish Parajuli ?
Creating a concurrent queue
创建并发队列
let concurrentQueue = DispatchQueue(label: "queuename", attributes: .concurrent)
concurrentQueue.sync {
}
Create a serial queue
创建串行队列
let serialQueue = DispatchQueue(label: "queuename")
serialQueue.sync {
}
Get main queue asynchronously
异步获取主队列
DispatchQueue.main.async {
}
Get main queue synchronously
同步获取主队列
DispatchQueue.main.sync {
}
To get one of the background thread
获取后台线程之一
DispatchQueue.global(qos: .background).async {
}
Xcode 8.2 beta 2:
Xcode 8.2 测试版 2:
To get one of the background thread
获取后台线程之一
DispatchQueue.global(qos: .default).async {
}
DispatchQueue.global().async {
// qos' default value is ′DispatchQoS.QoSClass.default`
}
If you want to learn about using these queues .See this answer
如果您想了解如何使用这些队列。请参阅此答案
回答by t1ser
Compiles under >=Swift 3. This example contains most of the syntax that we need.
在 >= Swift 3下编译。这个例子包含了我们需要的大部分语法。
QoS - new quality of service syntax
QoS - 新的服务质量语法
weak self
- to disrupt retain cycles
weak self
- 破坏保留周期
if self is not available, do nothing
如果 self 不可用,则什么都不做
async global utility queue
- for network query, does not wait for the result, it is a concurrent queue, the block (usually) does not wait when started. Exception for a concurrent queue could be, when its task limit has been previously reached, then the queue temporarily turns into a serial queue and waits until some previous task in that queue completes.
async global utility queue
- 用于网络查询,不等待结果,是一个并发队列,块(通常)在启动时不等待。并发队列的例外情况可能是,当先前已达到其任务限制时,该队列会暂时变为串行队列并等待该队列中的某个先前任务完成。
async main queue
- for touching the UI, the block does not wait for the result, but waits for its slot at the start. The main queue is a serial queue.
async main queue
- 对于触摸 UI,块不等待结果,而是在开始时等待其插槽。主队列是串行队列。
Of course, you need to add some error checking to this...
当然,您需要为此添加一些错误检查...
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
}
}
}
}
回答by R Thomas
Compiled in XCode 8, Swift 3 https://github.com/rpthomas/Jedisware
在 XCode 8、Swift 3 https://github.com/rpthomas/Jedisware 中编译
@IBAction func tap(_ sender: AnyObject) {
let thisEmail = "emailaddress.com"
let thisPassword = "myPassword"
DispatchQueue.global(qos: .background).async {
// Validate user input
let result = self.validate(thisEmail, password: thisPassword)
// Go back to the main thread to update the UI
DispatchQueue.main.async {
if !result
{
self.displayFailureAlert()
}
}
}
}
回答by Cosmin
Since the OP question has already been answered above I just want to add some speed considerations:
由于上面已经回答了 OP 问题,因此我只想添加一些速度方面的考虑:
It makes a lot of difference what priority class you assign to your async function in DispatchQueue.global.
在DispatchQueue.global 中分配给异步函数的优先级类有很大不同。
I don't recommend running tasks with the .backgroundthread priority especially on the iPhone X where the task seems to be allocated on the low power cores.
我不建议使用.background线程优先级运行任务,尤其是在 iPhone X 上,任务似乎分配在低功耗内核上。
Here is some real data from a computationally intensive function that reads from an XML file (with buffering) and performs data interpolation:
下面是一些来自计算密集型函数的真实数据,该函数从 XML 文件(带缓冲)读取并执行数据插值:
Device name / .background/ .utility/ .default/ .userInitiated/ .userInteractive
设备名称 / .background/ .utility/ .default/ .userInitiated/ .userInteractive
- iPhone X: 18.7s / 6.3s / 1.8s / 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:18.7s / 6.3s / 1.8s / 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
Note that the data set is not the same for all devices. It's the biggest on the iPhone X and the smallest on the iPhone 5s.
请注意,并非所有设备的数据集都相同。它是 iPhone X 上最大的,也是 iPhone 5s 上最小的。
回答by Asfand Shabbir
I did this and this is especially important if you want to refresh your UI to show new data without user noticing like in UITableView or UIPickerView.
我这样做了,如果你想刷新你的 UI 以显示新数据而不像 UITableView 或 UIPickerView 那样用户注意到,这尤其重要。
DispatchQueue.main.async
{
/*Write your thread code here*/
}
回答by Fritz Gerald Moran
DispatchQueue.main.async {
self.collectionView?.reloadData() // Depends if you were populating a collection view or table view
}
OperationQueue.main.addOperation {
self.lblGenre.text = self.movGenre
}
//use Operation Queue if you need to populate the objects(labels, imageview, textview) on your viewcontroller
//如果您需要在视图控制器上填充对象(标签、图像视图、文本视图),请使用操作队列
回答by gosborne3
let concurrentQueue = dispatch_queue_create("com.swift3.imageQueue", DISPATCH_QUEUE_CONCURRENT) //Swift 2 version
let concurrentQueue = DispatchQueue(label:"com.swift3.imageQueue", attributes: .concurrent) //Swift 3 version
I re-worked your code in Xcode 8, Swift 3 and the changes are marked in contrast to your Swift 2 version.
我在 Xcode 8、Swift 3 中重新编写了您的代码,这些更改与您的 Swift 2 版本形成对比。
回答by Hitesh Chauhan
DispatchQueue.main.async(execute: {
// write code
})
Serial Queue :
串行队列:
let serial = DispatchQueue(label: "Queuename")
serial.sync {
//Code Here
}
Concurrent queue :
并发队列:
let concurrent = DispatchQueue(label: "Queuename", attributes: .concurrent)
concurrent.sync {
//Code Here
}
回答by Amul4608
Swift 3
斯威夫特 3
you want call some closure in swift code then you want to change in storyboard ya any type off change belong to view your application will crash
您想在 swift 代码中调用一些闭包,然后您想在故事板中更改任何类型的更改属于查看您的应用程序将崩溃
but you want to use dispatch method your application will not crash
但是你想使用 dispatch 方法你的应用程序不会崩溃
async method
异步方法
DispatchQueue.main.async
{
//Write code here
}
sync method
同步方法
DispatchQueue.main.sync
{
//Write code here
}
回答by Joseph Mikko Manoza
For Swift 3
对于 Swift 3
DispatchQueue.main.async {
// Write your code here
}