Cómo crear cola de despacho en Swift 3
En Swift 2, pude crear cola con el siguiente código:
let concurrentQueue = dispatch_queue_create("com.swift3.imageQueue", DISPATCH_QUEUE_CONCURRENT)
Pero esto no compila en Swift 3.
¿Cuál es la forma preferida de escribir esto en Swift 3?
14 answers
Creando una cola concurrente
let concurrentQueue = DispatchQueue(label: "queuename", attributes: .concurrent)
concurrentQueue.sync {
}
Crear una cola de serie
let serialQueue = DispatchQueue(label: "queuename")
serialQueue.sync {
}
Obtener la cola principal de forma asíncrona
DispatchQueue.main.async {
}
Obtener la cola principal sincrónicamente
DispatchQueue.main.sync {
}
Para obtener uno de los hilos de fondo
DispatchQueue.global(qos: .background).async {
}
Xcode 8.2 beta 2:
Para obtener uno de los hilos de fondo
DispatchQueue.global(qos: .default).async {
}
DispatchQueue.global().async {
// qos' default value is ´DispatchQoS.QoSClass.default`
}
Si desea aprender sobre el uso de estas colas .Ver esta respuesta
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-08-25 16:43:49
Compila bajo Swift 3. Este ejemplo contiene la mayor parte de la sintaxis que necesitamos.
QoS-nueva sintaxis de calidad de servicio
weak self
- para interrumpir los ciclos de retención
Si el yo no está disponible, no hacer nada
async global background queue
- para consulta de red
async main queue
- por tocar la interfaz de usuario.
Por supuesto, debe agregar algunas comprobaciones de errores a esto...
DispatchQueue.global(qos: .background).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
}
}
}
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-07-26 13:09:32
Compilado en 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()
}
}
}
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-11-18 21:41:45
Hice esto y esto es especialmente importante si desea actualizar su interfaz de usuario para mostrar nuevos datos sin que el usuario lo note, como en UITableView o UIPickerView.
DispatchQueue.main.async
{
/*Write your thread code here*/
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-01-22 18:18:38
Dado que la pregunta de OP ya ha sido respondida anteriormente, solo quiero agregar algunas consideraciones de velocidad:
Hace mucha diferencia la clase de prioridad que asigne a su función async en DispatchQueue.global .
No recomiendo ejecutar tareas con el .antecedentes prioridad de hilo especialmente en el iPhone X donde la tarea parece estar asignada en los núcleos de baja potencia.
Aquí hay algunos datos reales de una función computacionalmente intensiva que lee desde un archivo XML (con buffering) y realiza la interpolación de datos:
Nombre del dispositivo / .antecedentes / .utilidad / .predeterminado / .Iniciado por el usuario / .UserInteractive
- iPhone X: 18.7 s / 6.3 s / 1.8 s / 1.8 s / 1.8 s
- iPhone 7: 4.6 s / 3.1 s / 3.0 s / 2.8 s / 2.6 s
- iPhone 5s: 7.3 s / 6.1 s / 4.0 s / 4.0 s / 3.8 s
Tenga en cuenta que el conjunto de datos no es el mismo para todos los dispositivos. Es el más grande en el iPhone X y el más pequeño en el iPhone 5s.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-05-16 12:45:07
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
He vuelto a trabajar su código en Xcode 8, Swift 3 y los cambios están marcados en contraste con su versión Swift 2.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-03-10 07:57:32
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
}
/ / utilice la cola de operaciones si necesita rellenar los objetos(labels, imageview, textview) en su viewcontroller
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-10 08:04:04
Swift 3
Desea llamar a algún cierre en el código swift, luego desea cambiar en storyboard ya cualquier tipo de cambio de pertenecer a ver que su aplicación se bloqueará
Pero desea usar el método de envío, su aplicación no se bloqueará
Método asincrónico
DispatchQueue.main.async
{
//Write code here
}
Método de sincronización
DispatchQueue.main.sync
{
//Write code here
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-18 09:46:06
DispatchQueue.main.async(execute: {
// write code
})
Cola en serie:
let serial = DispatchQueue(label: "Queuename")
serial.sync {
//Code Here
}
Cola concurrente:
let concurrent = DispatchQueue(label: "Queuename", attributes: .concurrent)
concurrent.sync {
//Code Here
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-19 07:42:24
Para Swift 3
DispatchQueue.main.async {
// Write your code here
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-08-23 03:49:15
let newQueue = DispatchQueue(label: "newname")
newQueue.sync {
// your code
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-10-12 07:37:21
Ahora es simplemente:
let serialQueue = DispatchQueue(label: "my serial queue")
El valor predeterminado es serial, para obtener concurrente, se utiliza el argumento atributos opcional .concurrente
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-09-10 00:36:05
Puede crear cola de despacho usando este código en swift 3.0
DispatchQueue.main.async
{
/*Write your code here*/
}
/* or */
let delayTime = DispatchTime.now() + Double(Int64(0.5 * Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC)
DispatchQueue.main.asyncAfter(deadline: delayTime)
{
/*Write your code here*/
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-05 15:20:17
DispatchQueue.main.async(execute: {
// code
})
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-16 05:58:50