【Swift】GCD多线程和BlockOperation实用代码块

22 篇文章 0 订阅
21 篇文章 0 订阅


loadingImage.swift

//自定义一个类

import UIKit
class Downloader {
    
    class func downloadImageWithURL(_ url:String) -> UIImage! {
        let data = try? Data(contentsOf: URL(string: url)!)
        return UIImage(data: data!)
    }
}

//ViewController上的代码


import UIKit

class ViewController: UIViewController {

    @IBOutlet weak var image1: UIImageView!
    @IBOutlet weak var image2: UIImageView!
    @IBOutlet weak var image3: UIImageView!
    @IBOutlet weak var image4: UIImageView!
    
    let imageUrls = [
        "https://dn-boxueio.qbox.me/image1-big.jpg",
        "https://dn-boxueio.qbox.me/image2-big.jpg",
        "https://dn-boxueio.qbox.me/image3-big.jpg",
        "https://dn-boxueio.qbox.me/image4-big.jpg"
    ]
    
    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.
    }

    @IBAction func clearDownload(_ sender: UIButton) {
        self.image1.image = nil
        self.image2.image = nil
        self.image3.image = nil
        self.image4.image = nil
        
        URLCache.shared.removeAllCachedResponses()
    }

     func loadImageWithURL(_ url:String) -> UIImage! {
        let data = try? Data(contentsOf: URL(string: url)!)
        return UIImage(data: data!)
        
         }

    
    @IBAction func downloadImages(_ sender: UIButton) {
        
      
        var currQueue = DispatchQueue.global(qos: .default)
      //  currQueue = DispatchQueue(label: "com.boxueio.images", attributes: .concurrent)
        //并行
        currQueue=DispatchQueue(label: "currqueue1", qos: .default, attributes: .concurrent)
        
        // dispatch_async
        currQueue.async(execute: {
            let img1 = self.loadImageWithURL(self.imageUrls[0])
            DispatchQueue.main.async(execute: {
                self.image1.image = img1
                self.image1.clipsToBounds = true
            })
        })
        
        currQueue.async(execute: {
            let img2 = self.loadImageWithURL(self.imageUrls[1])
            DispatchQueue.main.async(execute: {
                self.image2.image = img2
                self.image2.clipsToBounds = true
            })
        })
        
        currQueue.async(execute: {
            let img3 = Downloader.downloadImageWithURL(self.imageUrls[2])
            DispatchQueue.main.async(execute: {
                self.image3.image = img3
                self.image3.clipsToBounds = true
            })
        })
        
        currQueue.async(execute: {
            let img4 = Downloader.downloadImageWithURL(self.imageUrls[3])
            DispatchQueue.main.async(execute: {
                self.image4.image = img4
                self.image4.clipsToBounds = true
            })
        })
    }
}

//Operation Queue

//
//  ViewController.swift


import UIKit

class ViewController: UIViewController {

    @IBOutlet weak var image1: UIImageView!
    @IBOutlet weak var image2: UIImageView!
    @IBOutlet weak var image3: UIImageView!
    @IBOutlet weak var image4: UIImageView!
    
    let imageUrls = [
        "https://dn-boxueio.qbox.me/image1-big.jpg",
        "https://dn-boxueio.qbox.me/image2-big.jpg",
        "https://dn-boxueio.qbox.me/image3-big.jpg",
        "https://dn-boxueio.qbox.me/image4-big.jpg"
    ]
    
    override func viewDidLoad() {
        super.viewDidLoad()
      //  present(<#T##viewControllerToPresent: UIViewController##UIViewController#>, animated: <#T##Bool#>, completion: nil)
        // 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.
    }

    @IBAction func clearDownload(_ sender: UIButton) {
        
      //  self.image1.image=UIImage(named: <#T##String#>)
        
        self.image1.image = nil
        self.image2.image = nil
        self.image3.image = nil
        self.image4.image = nil
        
        URLCache.shared.removeAllCachedResponses()
    }

    let queue = OperationQueue()
    
    @IBAction func cancelDownload(_ sender: AnyObject) {
        self.queue.cancelAllOperations()
    }
    
    @IBAction func downloadImages(_ sender: UIButton) {
       
        
//        queue.addOperation({
//            
//            
//            let img1 = Downloader.downloadImageWithURL(self.imageUrls[0])
//            
//            OperationQueue.main.addOperation({
//                self.image1.image = img1
//                self.image1.clipsToBounds = true
//            })
//        })
//        
//        
        let op1 = BlockOperation(block: {
            let img1 = Downloader.downloadImageWithURL(self.imageUrls[0])
            
            OperationQueue.main.addOperation({
                self.image1.image = img1
                self.image1.clipsToBounds = true
            })
        })
        op1.completionBlock = { print("image1 downloaded") }
        
        let op2 = BlockOperation(block: {
            let img2 = Downloader.downloadImageWithURL(self.imageUrls[1])
            
            OperationQueue.main.addOperation({
                self.image2.image = img2
                self.image2.clipsToBounds = true
            })
        })
        op2.completionBlock = { print("image2 downloaded") }
        
        
        
        let op3 = BlockOperation(block: {
            let img3 = Downloader.downloadImageWithURL(self.imageUrls[2])
            
            OperationQueue.main.addOperation({
                self.image3.image = img3
                self.image3.clipsToBounds = true
            })
        })
        op3.completionBlock = { print("image3 downloaded") }
        
        
        
        let op4 = BlockOperation(block: {
            let img4 = Downloader.downloadImageWithURL(self.imageUrls[3])
            
            OperationQueue.main.addOperation({
                self.image4.image = img4
                self.image4.clipsToBounds = true
            })
        })
        op4.completionBlock = { print("image4 downloaded") }
        
   //     op3.addDependency(op4)
       // op2.addDependency(op3)
        
        queue.addOperation (op1)
        queue.addOperation(op4)
        queue.addOperation(op3)
        queue.addOperation(op2)
    }
}



线程并行 下载顺序

//op1先执行 op3 op 2 op4
// 1 3 2 4
op3.addDependency(op1)
op2.addDependency(op3)
op4.addDependency(op2)


queue.addOperation(op1)
queue.addOperation(op2)
queue.addOperation(op3)
queue.addOperation(op4)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值