Created
December 25, 2015 02:36
-
-
Save alfredcc/06a53514369345188384 to your computer and use it in GitHub Desktop.
You can use enum and protocol extension to provide GCD convenience API:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
You can use enum and protocol extension to provide GCD convenience API: | |
``` | |
protocol ExcutableQueue { | |
var queue: dispatch_queue_t { get } | |
} | |
extension ExcutableQueue { | |
func execute(closure: () -> Void) { | |
dispatch_async(queue, closure) | |
} | |
} | |
enum Queue: ExcutableQueue { | |
case Main | |
case UserInteractive | |
case UserInitiated | |
case Utility | |
case Background | |
var queue: dispatch_queue_t { | |
switch self { | |
case .Main: | |
return dispatch_get_main_queue() | |
case .UserInteractive: | |
return dispatch_get_global_queue(QOS_CLASS_USER_INTERACTIVE, 0) | |
case .UserInitiated: | |
return dispatch_get_global_queue(QOS_CLASS_USER_INITIATED, 0) | |
case .Utility: | |
return dispatch_get_global_queue(QOS_CLASS_UTILITY, 0) | |
case .Background: | |
return dispatch_get_global_queue(QOS_CLASS_BACKGROUND, 0) | |
} | |
} | |
} | |
enum SerialQueue: String, ExcutableQueue { | |
case DownLoadImage = "myApp.SerialQueue.DownLoadImage" | |
case UpLoadFile = "myApp.SerialQueue.UpLoadFile" | |
var queue: dispatch_queue_t { | |
return dispatch_queue_create(rawValue, DISPATCH_QUEUE_SERIAL) | |
} | |
} | |
``` | |
Download Something could write like this: | |
``` | |
Queue.UserInitiated.execute { | |
let url = NSURL(string: "http://image.jpg")! | |
let data = NSData(contentsOfURL: url)! | |
let image = UIImage(data: data) | |
Queue.Main.execute { | |
imageView.image = image | |
} | |
} | |
``` |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment