使用Serial queue處理并發(fā)任務
1.單條隊列
import UIKit
class ViewController: UIViewController {
@IBOutlet var imageViewArr: [UIImageView]!
let imageUrls = ["https://xxx.com/1.jpg","https://xxx.com/2.jpg","https://xxx.com/3.jpg","https://xxx.com/4.jpg"]
override func viewDidLoad() {
super.viewDidLoad()
}
@IBAction func downloadImages(sender: UIButton) {
// Add task
let serialQueue1 = dispatch_queue_create(
"task1", DISPATCH_QUEUE_SERIAL)
dispatch_async(serialQueue1) { () -> Void in
for i in 0..<4 {
let imageViewUrls = Downloader.downloadImageWithURL(self.imageUrls[i])
// UI需要在主線程下更新
dispatch_async(dispatch_get_main_queue(), { () -> Void in
self.imageViewArr[i].image = imageViewUrls
//self.imageViewArr[i].clipsToBounds = true
})
}
}
}
@IBAction func ClearDownData(sender: UIButton) {
for i in 0...3 {
imageViewArr[i].image = nil
}
}
}
// -------------
class Downloader {
class func downloadImageWithURL(url:String) -> UIImage! {
let data = NSData(contentsOfURL: NSURL(string: url)!)
return UIImage(data: data!)
}
}
1.1多條隊列
let serialQueue1 = dispatch_queue_create(
"task1", DISPATCH_QUEUE_SERIAL)
dispatch_async(serialQueue1) { () -> Void in
let image0 = Downloader.downloadImageWithURL(self.imageUrls[0])
let image2 = Downloader.downloadImageWithURL(self.imageUrls[1])
dispatch_async(dispatch_get_main_queue(), { () -> Void in
self.imageViewArr[0].image = image0
self.imageViewArr[2].image = image2
})
}
let serialQueue2 = dispatch_queue_create("task2", DISPATCH_QUEUE_SERIAL)
dispatch_async(serialQueue2, { () -> Void in
let image1 = Downloader.downloadImageWithURL(self.imageUrls[1])
let image3 = Downloader.downloadImageWithURL(self.imageUrls[3])
dispatch_async(dispatch_get_main_queue(), { () -> Void in
self.imageViewArr[1].image = image1
self.imageViewArr[3].image = image3
})
})