KillerRabbitTHGDispatch 模块
KillerRabbit 是 THGDispatch 模块,包括 GCD bits:Queues, Groups, Timer, Semaphore 等等。
使用:
执行异步闭包:
Dispatch().async(.Background) { doSomething() }
在后台队列执行异步闭包:
Dispatch().async(.Background) { doSomething() }.notify(.Main) { dearMainThreadImDone() }
执行一个异步闭包并等候 3 秒:
Dispatch().async(.Background) { doSomething() }.wait(3) == false { itTimedOutImSad() } else { itWasSuccessfulAndMyLifeHasMeaning() }
执行一些异步任务:
DispatchGroup().async(.Background) { doSomething(1) }.async(.Utility) { doSomething(2) }.async(.High) { doSomethingUrgently(3) }.wait()
或者:
let group = DispatchGroup() group.async(.Background) { doSomething(1) }.async(.Utility) { doSomething(2) }.async(.High) { doSomethingUrgently(3) }if group.wait(10) == true { handstandAndCartwheel() }
执行一个异步任务,同步一个 Semaphore:
let semaphore = DispatchSemaphore(initialValue: 0)// start a NSURLSession to get some data from our imaginary command line tool.let task = session.dataTaskWithRequest(request) { (data, response, error) -> Void in if data != nil { let dataString: String = NSString(data: data, encoding: NSUTF8StringEncoding)! as String json = JSON(string: dataString) } semaphore.signal() } task.resume() semaphore.wait()
评论