Beginnings of a GCD wrapper in swift
import Foundation | |
class dispatch | |
{ | |
class async | |
{ | |
class func bg(block: dispatch_block_t) { | |
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), block) | |
} | |
class func main(block: dispatch_block_t) { | |
dispatch_async(dispatch_get_main_queue(), block) | |
} | |
} | |
class sync | |
{ | |
class func bg(block: dispatch_block_t) { | |
dispatch_sync(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), block) | |
} | |
class func main(block: dispatch_block_t) { | |
if NSThread.isMainThread { | |
block() | |
} | |
else { | |
dispatch_sync(dispatch_get_main_queue(), block) | |
} | |
} | |
} | |
// after by @stanislavfeldman | |
class after { | |
class func bg(when: dispatch_time_t, block: dispatch_block_t) { | |
dispatch_after(when, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0)!, block) | |
} | |
class func main(when: dispatch_time_t, block: dispatch_block_t) { | |
dispatch_after(when, dispatch_get_main_queue(), block) | |
} | |
} | |
} | |
import UIKit | |
import QuartzCore | |
class ViewController: UIViewController { | |
@IBOutlet weak var label: UILabel | |
@IBOutlet weak var counter: UILabel | |
override func viewDidLoad() { | |
super.viewDidLoad() | |
dispatch.async.bg { | |
var count = 0; | |
for index in 0..10000000 { | |
dispatch.sync.main { | |
self.counter.text = "\(index)" | |
} | |
} | |
} | |
} | |
@IBAction func clickety() { | |
label.text = NSDate.date().description | |
} | |
} | |
This comment has been minimized.
This comment has been minimized.
Ah yes. Fixed. ^^ |
This comment has been minimized.
This comment has been minimized.
赞(Good) ! |
This comment has been minimized.
This comment has been minimized.
Inferis, take a look at my fork https://gist.github.com/stanislavfeldman/0f37794b369eb6da98cc |
This comment has been minimized.
This comment has been minimized.
@Inferis I have a variation on your wrapper that adds more queues (interactive, user, utility) and implements (optional) safe sync for all queues (probably not needed beside main). I needed to reverse the call order to make this manageable: dispatch.main.sync {print("hello possible deadlock")}
dispatch.utility.async {print("hello")}
dispatch.main.safeSync {print("hello from the main thread")}
dispatch.main.after(2.5) {print("in main after 2.5 seconds")} @stanfeldman I don't think your "after" methods do what you think they do. https://gist.github.com/amw/9d62f247d0de3fa08e5facc59bc91037 |
This comment has been minimized.
This comment has been minimized.
I've added support for dispatch groups and blogged about my implementation. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This comment has been minimized.
@Inferis you can make it even cleaner and get rid of the extra parenthesis when calling it (also you do'nt need the semi-colons😉