Swift 延时执行

来源:互联网 发布:电子杂志app软件哪个好 编辑:程序博客网 时间:2024/06/13 23:04

采用 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)
}

执行方法

delay(2) { println("2 秒后输出") }


取消方法:

let task = delay(5) { println("拨打 110") }
 
cancel(task)




0 0
原创粉丝点击