Swift 学习笔记(八).md
ios swift 多线程(队列) //这篇笔记是看了这篇文章后的总结
-
用
DispatchQueue
创建队列DispatchQueue( label: String, qos: DispatchQoS, attributes: DispatchQueue.Attributes, autoreleaseFrequency: DispatchQueue.AutoreleaseFrequency, target: DispatchQueue? )
其中参数lable 是必须并独一无二的
你唯一要做的事就是为你的队列提供一个独一无二的标签(label)。使用一个反向的 DNS 符号(”com.appcoda.myqueue”)就很好,因为用它很容易创造一个独一无二的标签,甚至连苹果公司都是这样建议的。尽管如此,这并不是强制性的,你可以使用你喜欢的任何字符串,只要这个字符串是唯一的。除此之外,上面的构造方法并不是创建队列的唯一方式。在初始化队列的时候可以提供更多的参数,我们会在后面的篇幅中谈论到它。
最简单的创建队列的方式就是
let queue = DispatchQueue(label: "com.appcoda.myqueue")
-
启动队列:
queue.async {<code>}
//异步。主队列与此队列同时运行queue.sync {<code>}
//同步。主队列会等待此队列运行结束再运行 -
队列优先级(QoS)
userInteractive userInitiated default utility background unspecified
//Apple用户至上的体现 这里是关于各个优先级的官方解释 QoS直接放进创建队列时的qos参数中
let queue1 = DispatchQueue(label: "com.appcoda.queue1", qos: .userInitiated) let queue2 = DispatchQueue(label: "com.appcoda.queue2", qos: .background)
优先级的高低主要影响系统资源的分配//并不意味着低优先级必须等待高优先级运行结束才执行 主队列拥有最高的优先级
-
并行队列
attributes
参数 创建并行队列let anotherQueue = DispatchQueue(label: "com.appcoda.anotherQueue", qos: .utility, attributes: .concurren)
attributes: .concurren
参数 未设置.concurren
attributes: .initiallyInactive
会在调用activate()
方法时才启动队列也可以同时设置两个参数
attributes: [.concurrent, .initiallyInactive]
-
延迟执行
let delayQueue = DispatchQueue(lable: "com.aiqg") //创建队列 let time: DispatchTimeInterval = .seconds(2) //设置一个时间 delayQueue.asyncAfter(deadline: .now() + time) { <code> } /* 也可以这样 delayQueue.asyncAfter(deadline: .now() + 2.0) { <code> } */
-
全局队列/主队列 全局队列是系统后台的队列
let globalQueue = DispatchQueue.global()
主队列一般用作更新UI
DispatchQueue.main.async { <code> }
-
使用 DispatchWorkItem 对象
func useWorkItem() { var value = 10 let workItem = DispatchWorkItem { value += 5 } } let queue = DispatchQueue.global() /*queue.async { workItem.perform() }这部分可以用下句代替*/ queue.async(execute: workItem)
notify
会在workItem运行结束后运行//相当于最后一项工作workItem.notify(queue: DispatchQueue.main) { print("value = ", value) }
//课堂草稿⬇️
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var imageView: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
//=======================================================
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
//simpleQueues()
//queuesWithQoS()
// concurrentQueues()
// //用于激活.initiallyInactive 不活动的队列
// if let queue = inactiveQueue {
// queue.activate()
// }
//queueWithDelay()
//fetchImage()
//useWorkItem()
}
func simpleQueues() {
let queue = DispatchQueue(label: "com.aiqg")
queue.async {
for i in 10..<20 {
print("\(i)")
}
}
//主队列
for i in 0..<10 {
print("\(i)")
}
}
func queuesWithQoS() {
//user为高优先级 ///主线程最高
let queue0 = DispatchQueue(label: "com.tryQoS0", qos:DispatchQoS.background)//低优先级
let queue1 = DispatchQueue(label: "com.tryQoS1", qos:DispatchQoS.utility)
queue0.async {
for i in 0..<10 {
print("🔵\(i)")
}
}
queue1.async {
for i in 10..<20 {
print("🔴\(i)")
}
}
for i in 1000..<1010 {
print("Ⓜ️", i)
}
}
//并行队列
var inactiveQueue: DispatchQueue! //不活动的队列
func concurrentQueues() {
//let anotherQueue = DispatchQueue(label: "com.another", qos: .utility)
//let anotherQueue = DispatchQueue(label: "com.another", qos: .utility, attributes: .concurrent)
let anotherQueue = DispatchQueue(label: "com.another", qos: .utility, attributes: [.initiallyInactive, .concurrent])//不活动+并行
inactiveQueue = anotherQueue
anotherQueue.async {
for i in 0..<10 {
print("⚪️\(i)")
}
}
anotherQueue.async {
for i in 100..<110 {
print("🔴\(i)")
}
}
anotherQueue.async {
for i in 1000..<1010 {
print("🔵\(i)")
}
}
}
func queueWithDelay() {
let delayQueue = DispatchQueue(label: "com.delay", qos: .userInitiated)
print(Date())
let additionalTime: DispatchTimeInterval = .seconds(2)
//启动延迟队列
delayQueue.asyncAfter(deadline: .now() + additionalTime) {
print(Date())
}
}
func fetchImage() {
// let globalQueue = DispatchQueue.global(qos: .background) //全局队列
// globalQueue.async {
// for i in 0..<10 {
// print("🔴\(i)")
// }
// }
let imageURL: URL = URL(string: "http://www.appcoda.com/wp-content/uploads/2015/12/blog-logo-dark-400.png")!
(URLSession(configuration: URLSessionConfiguration.default)).dataTask(with: imageURL, completionHandler: {(imageData, response, error) in
if let data = imageData {
print("完成")
DispatchQueue.main.async {
self.imageView.image = UIImage(data: data) //主队列中更新UI
}
}
}).resume()
}
func useWorkItem() {
var value = 10
let workItem = DispatchWorkItem {
value += 5
}
//在全局队列中运行
workItem.perform() //在主队列上运行 =15
let queue = DispatchQueue.global(qos: .utility)
queue.async(execute: workItem) //在全局队列运行 =20
workItem.notify(queue: DispatchQueue.main) {
print("value = \(value)")
}
}
}