如何在swift中使用后台线程? [英] How to use background thread in swift?

查看:143
本文介绍了如何在swift中使用后台线程?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在swift中使用线程?

How to use threading in swift?

dispatchOnMainThread:^{

    NSLog(@"Block Executed On %s", dispatch_queue_get_label(dispatch_get_current_queue()));

}];


推荐答案

Swift 3.0 +



很多已经现代化。在后台线程上运行的东西如下所示:

Swift 3.0+

A lot has been modernized in Swift 3.0. Running something on the background thread looks like this:

DispatchQueue.global(qos: .background).async {
    print("This is run on the background queue")

    DispatchQueue.main.async {
        print("This is run on the main queue, after the previous code in outer block")
    }
}



Swift 1.2到2.3



Swift 1.2 through 2.3

let qualityOfServiceClass = QOS_CLASS_BACKGROUND
let backgroundQueue = dispatch_get_global_queue(qualityOfServiceClass, 0)
dispatch_async(backgroundQueue, {
    print("This is run on the background queue")

    dispatch_async(dispatch_get_main_queue(), { () -> Void in
        print("This is run on the main queue, after the previous code in outer block")
    })
})



Pre Swift 1.2 - 已知问题



从Swift 1.1开始,如果没有一些修改,Apple不支持上述语法秒。传递 QOS_CLASS_BACKGROUND 实际上没有用,而是使用 Int(QOS_CLASS_BACKGROUND.value)

Pre Swift 1.2 – Known issue

As of Swift 1.1 Apple didn't support the above syntax without some modifications. Passing QOS_CLASS_BACKGROUND didn't actually work, instead use Int(QOS_CLASS_BACKGROUND.value).

有关详细信息,请参阅苹果文档

For more information see Apples documentation

这篇关于如何在swift中使用后台线程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆