swift3多線程學(xué)習(xí)筆記

當(dāng)通過(guò)url來(lái)給UIImageView設(shè)置圖片的時(shí)候需要下載圖片,如果在主線程中執(zhí)行下載圖片并設(shè)置圖片會(huì)導(dǎo)致在下載圖片的時(shí)候界面卡死。通過(guò)多線程可以解決下載任務(wù)導(dǎo)致界面卡死的問(wèn)題。

1、創(chuàng)建并使用額外的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進(jìn)行多任務(wù)處理

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)
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • iOS開(kāi)發(fā)中常用的幾種多線程方案,簡(jiǎn)單做個(gè)小結(jié),方便日后查閱。 Pthreads NSThead GCD NSOp...
    acqiang閱讀 473評(píng)論 0 4
  • iOS開(kāi)發(fā)中常用的幾種多線程方案,簡(jiǎn)單做個(gè)小結(jié),方便日后查閱。 NSThead GCD NSOperation &...
    木木小林醬閱讀 368評(píng)論 0 1
  • 在這篇文章中,我將為你整理一下 iOS 開(kāi)發(fā)中幾種多線程方案,以及其使用方法和注意事項(xiàng)。當(dāng)然也會(huì)給出幾種多線程的案...
    張戰(zhàn)威ican閱讀 693評(píng)論 0 0
  • 學(xué)習(xí)多線程,轉(zhuǎn)載兩篇大神的帖子,留著以后回顧!第一篇:關(guān)于iOS多線程,你看我就夠了 第二篇:GCD使用經(jīng)驗(yàn)與技巧...
    John_LS閱讀 740評(píng)論 0 3
  • 其實(shí),我特別想寫(xiě)寫(xiě)自己的母親。這個(gè)念頭有一些日子了,雖然之前在個(gè)人成長(zhǎng)自傳中也專(zhuān)門(mén)寫(xiě)過(guò)母親,但那畢竟是幾年前我眼中...
    幻夢(mèng)一場(chǎng)閱讀 281評(píng)論 0 2

友情鏈接更多精彩內(nèi)容