ios多線程開發基礎

來源:互聯網
上載者:User

標籤:nts   main   jpg   queue類   指定   patch   線程   sof   tun   

多線程編程:下載資料時,開闢子線程,減少阻塞時間,和主線程並發運行,提升使用者體驗

1.Thread

1>建立Thread對象,帶一selector方法,調用start方法,開啟子線程

2>thread初始化內建的selector方法中請求資料

3>資料請回來後,調用self的performSelectorOnMainThread方法,又帶一selector,以及相應的參數,通常是請求回的資料,如果不是self,將找不到selector方法//必須是self

4>對請求回的資料進行處理,實現UI更新

 

2.GCD-great central dispatch

1>使用DispatchQueue類型建立隊列

2>dispatch_queue.async{

//請求資料代碼

//切回主線程

DispatchQueue.main.async{

//更新UI代碼

}

}

 

3.Operation

1>使用OperationQueue類型建立隊列

2>使用BlockOperation類型建立操作,操作中先請求資料,在調用self的performSelectorOnMainThread方法切回主線程,最後更新UI

code:

        let operation = BlockOperation { 

            let url = URL(string:"http://pic37.nipic.com/20131227/17514635_163144299116_2.jpg")

            let data = NSData(contentsOf: url!) as! Data

            let img = UIImage(data: data)

            //用指定方法更新UI,調用者必須為當前的viewController!!!

            self.performSelector(onMainThread: #selector(self.updateImage(image:)), with: img, waitUntilDone: false)

            

        }

        queue.addOperation(operation)

3>將操作排入佇列

ios多線程開發基礎

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.