swift3多线程学习笔记

当通过url来给UIImageView设置图片的时候需要下载图片,如果在主线程中执行下载图片并设置图片会导致在下载图片的时候界面卡死。通过多线程可以解决下载任务导致界面卡死的问题。

1、创建并使用额外的Serie Queue

letseriesQueue =DispatchQueue(label:"textGCD")

seriesQueue.async{

  letimage =DownloadManager.download(url:self.imageUrls[0])

  DispatchQueue.main.sync{

    self.image.image= image

    self.image.clipsToBounds=true

  }
}

2、使用Concurrent queue并行处理

let curQueue = DispatchQueue.global()
curQueue.async {
    let image = DownloadManager.download(url: self.imageUrls[0])
    DispatchQueue.main.sync {
        self.image1.image = image
        self.image1.clipsToBounds = true
    }
}

3、使用Operation Queue进行多任务处理

let operationQueue = OperationQueue()
operationQueue.addOperation {
    let image = DownloadManager.download(url: self.imageUrls[0])
    OperationQueue.main.addOperation({
        self.image1.image = image
        self.image1.clipsToBounds = true
        
    })
}

let operation2 = BlockOperation.init {
    let image = DownloadManager.download(url: self.imageUrls[1])
    OperationQueue.main.addOperation({
        self.image2.image = image
        self.image2.clipsToBounds = true
    })
}

let operation3 = BlockOperation.init {
    let image = DownloadManager.download(url: self.imageUrls[2])
    OperationQueue.main.addOperation({
        self.image3.image = image
        self.image3.clipsToBounds = true
    })
}

let operation4 = BlockOperation.init {
    let image = DownloadManager.download(url: self.imageUrls[3])
    OperationQueue.main.addOperation({
        self.image4.image = image
        self.image4.clipsToBounds = true
    })
}

operation2.addDependency(operation3)
operation3.addDependency(operation4)

operation2.completionBlock = { print("task completion")}
operationQueue.addOperation(operation2)
operationQueue.addOperation(operation3)
operationQueue.addOperation(operation4)
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • iOS开发中常用的几种多线程方案,简单做个小结,方便日后查阅。 Pthreads NSThead GCD NSOp...
    acqiang阅读 3,110评论 0 4
  • iOS开发中常用的几种多线程方案,简单做个小结,方便日后查阅。 NSThead GCD NSOperation &...
    木木小林酱阅读 2,555评论 0 1
  • 在这篇文章中,我将为你整理一下 iOS 开发中几种多线程方案,以及其使用方法和注意事项。当然也会给出几种多线程的案...
    张战威ican阅读 3,725评论 0 0
  • 学习多线程,转载两篇大神的帖子,留着以后回顾!第一篇:关于iOS多线程,你看我就够了 第二篇:GCD使用经验与技巧...
    John_LS阅读 3,790评论 0 3
  • 其实,我特别想写写自己的母亲。这个念头有一些日子了,虽然之前在个人成长自传中也专门写过母亲,但那毕竟是几年前我眼中...
    幻梦一场阅读 1,547评论 0 2