采用 GCD 模式调用:
// 创建目标队列
let workingQueue = dispatch_queue_create(
"my_queue"
, nil)
// 派发到刚创建的队列中,GCD 会负责进行线程调度
dispatch_async(workingQueue) {
// 在 workingQueue 中异步进行
println(
"努力工作"
)
NSThread.sleepForTimeInterval(2)
// 模拟两秒的执行时间
dispatch_async(dispatch_get_main_queue()) {
// 返回到主线程更新 UI
println(
"结束工作,更新 UI"
)
}
}
实现延迟调用:
let
time
: NSTimeInterval = 2.0
let delay = dispatch_time(DISPATCH_TIME_NOW,
Int64(
time
* Double(NSEC_PER_SEC)))
dispatch_after(delay, dispatch_get_main_queue()) {
println(
"2 秒后输出"
)
}
完整实例:
import Foundation
typealias Task = (cancel : Bool) -> ()
func delay(
time
:NSTimeInterval, task:()->()) -> Task? {
func dispatch_later(block:()->()) {
dispatch_after(
dispatch_time(
DISPATCH_TIME_NOW,
Int64(
time
* Double(NSEC_PER_SEC))),
dispatch_get_main_queue(),
block)
}
var closure: dispatch_block_t? = task
var result: Task?
let delayedClosure: Task = {
cancel in
if
let internalClosure = closure {
if
(cancel ==
false
) {
dispatch_async(dispatch_get_main_queue(), internalClosure);
}
}
closure = nil
result = nil
}
result = delayedClosure
dispatch_later {
if
let delayedClosure = result {
delayedClosure(cancel:
false
)
}
}
return
result;
}
func cancel(task:Task?) {
task?(cancel:
true
)
}
执行方法
:
|
取消方法:
let task = delay(5) { println(
"拨打 110"
) }
cancel(task)
版权声明:本文为qq_18951479原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。