dispatch_after - GCD in Swift?

前端 未结 25 2427
心在旅途
心在旅途 2020-11-21 06:07

I\'ve gone through the iBook from Apple, and couldn\'t find any definition of it:

Can someone explain the structure of dispatch_after?

d         


        
25条回答
  •  别跟我提以往
    2020-11-21 06:47

    matt's syntax is very nice and if you need to invalidate the block, you may want to use this :

    typealias dispatch_cancelable_closure = (cancel : Bool) -> Void
    
    func delay(time:NSTimeInterval, closure:()->Void) ->  dispatch_cancelable_closure? {
    
        func dispatch_later(clsr:()->Void) {
            dispatch_after(
                dispatch_time(
                    DISPATCH_TIME_NOW,
                    Int64(time * Double(NSEC_PER_SEC))
                ),
                dispatch_get_main_queue(), clsr)
        }
    
        var closure:dispatch_block_t? = closure
        var cancelableClosure:dispatch_cancelable_closure?
    
        let delayedClosure:dispatch_cancelable_closure = { cancel in
            if closure != nil {
                if (cancel == false) {
                    dispatch_async(dispatch_get_main_queue(), closure!);
                }
            }
            closure = nil
            cancelableClosure = nil
        }
    
        cancelableClosure = delayedClosure
    
        dispatch_later {
            if let delayedClosure = cancelableClosure {
                delayedClosure(cancel: false)
            }
        }
    
        return cancelableClosure;
    }
    
    func cancel_delay(closure:dispatch_cancelable_closure?) {
    
        if closure != nil {
            closure!(cancel: true)
        }
    }
    

    Use as follow

    let retVal = delay(2.0) {
        println("Later")
    }
    delay(1.0) {
        cancel_delay(retVal)
    }
    

    credits

    Link above seems to be down. Original Objc code from Github

提交回复
热议问题