当前位置:   article > 正文

Swift3 concurrency

swift_concurrency

转自我的github: https://github.com/uniquejava/iOSConcurrencyDemo

swift3 concurrency

This repo is the steps breaking down from this excellent tutorial and an update for swift3 + xcode8. I seperated each step into its own commit, you can check the commit history for details.

The major difference is on GCD part, for NSOperation part, the changes are minor.

输入图片说明

A compact example

Example from here qos - new quality of service syntax

weak self - to disrupt retain cycles

async global background queue - for network query

async main queue - for touching the UI.

Of course you need to add some error checking to this...

  1. DispatchQueue.global(qos: .background).async { [weak self]
  2. () -> Void in
  3. self?.flickrPhoto.loadLargeImage {
  4. loadedFlickrPhoto, error in
  5. if error != nil {
  6. print("error:\(error)")
  7. } else {
  8. DispatchQueue.main.async {
  9. () -> Void in
  10. activityIndicator.removeFromSuperview()
  11. self?.imageView.image = self?.flickrPhoto.largeImage
  12. }
  13. }
  14. }
  15. }

Swift2 GCD cheetsheet

输入图片说明

get main queue

swift2 version:

dispatch_get_main_queue()

swift3 version:

DispatchQueue.main    

global concurrent queue

swift2 version:

let queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)

swift3 version:

let queue = DispatchQueue.global(qos: .default) 

custom serial queue

swift2 version:

let queue = dispatch_queue_create("com.cyper.xxx", DISPATCH_QUEUE_SERIAL)

swift3 version:

let queue = DispatchQueue(label: "com.cyper.xxx")

DispatchQueue by default is serial queue, you don't have to specify it in the initializer.

custom concurrent queue

swift2 version:

let queue = dispatch_queue_create("com.cyper.xxx", DISPATCH_QUEUE_CONCURRENT)

swift3 version:

let queue = DispatchQueue(label: "com.cyper.xxx", qos: .userInitiated, attributes: .concurrent)

NSOperationQueue

  1. Removed the NS prefix
  2. Simplified the method name
  3. You can use xcode auto-fix

References

http://www.appcoda.com/ios-concurrency/

https://medium.com/swift-and-ios-writing/a-quick-look-at-gcd-and-swift-3-732bef6e1838#.ueryj2b2h

https://www.logcg.com/archives/2040.html

http://stackoverflow.com/questions/37805885/how-to-create-dispatch-queue-in-swift-3

Code

https://github.com/uniquejava/iOSConcurrencyDemo/blob/master/iOSConcurrencyDemo/ViewController.swift

转载于:https://my.oschina.net/uniquejava/blog/776737

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/繁依Fanyi0/article/detail/460776
推荐阅读
相关标签
  

闽ICP备14008679号