GCD
常用写法:
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) {
doSomething() // 耗时操作
dispatch_async(dispatch_get_main_queue()) {
updateUI() // 更新主线程
}
}
如果运行一系列的任务,希望当任务全部结束后运行另一个任务:
let queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)
let group = dispatch_group_create()
for (id obj in array) {
dispatch_group_async(group, queue) {
self.doWork(obj)
}
}
dispatch_group_notify(group, queue) {
self.doneWork
}
// 如果是在OS X 10.8或iOS 6以及之后版本中使用,Dispatch Queue将会由ARC自动管理,如果是在此之前的版本,需要自己手动释放
// dispatch_release(group)
延时调用:
func after(inSeconds seconds: Double, closure: () -> ()) {
let delayTime = dispatch_time(DISPATCH_TIME_NOW, Int64(seconds * Double(NSEC_PER_SEC)))
dispatch_after(delayTime, dispatch_get_main_queue(), closure)
}
after(0.4) {
// do stuff
}