美文网首页
Swift 3.0 —GCD

Swift 3.0 —GCD

作者: BeginnerMind | 来源:发表于2017-07-27 15:44 被阅读10次

    常用场景:使用global queue完成操作后切换到main queue更新UI

    DispatchQueue.global().async {
        //code
        DispatchQueue.main.async {
            //update ui
        }
    }
    

    使用Custom Queue

    let serialQueue = DispatchQueue(label: "com.serialQueue.dispatch")
    let concurrentQueue = DispatchQueue(label: "com.concurrentQueue.dispatch", qos: .background, attributes:.concurrent)
    

    延迟调用

    let delay = DispatchTime.now() + DispatchTimeInterval.seconds(3)
    DispatchQueue.main.asyncAfter(deadline: delay) { 
        print("delay 3 seconds")
    }
    

    使用Group管理多个Queue,可以使用notify等到结束通知,使用wait等待group中所有操作执行完毕

    let group = DispatchGroup()
    
    let bookQueue = DispatchQueue(label: "com.group.book")
    bookQueue.async(group: group) { 
        //down load books
    }
    
    let videoQueue = DispatchQueue(label: "com.group.video")
    videoQueue.async(group: group) { 
        //down load videos
    }
    group.notify(queue: DispatchQueue.main) { 
        //download finished
    }
    group.wait()
    

    DispatchWorkItem代替了原先的dispatch_block_t

    let workItem = DispatchWorkItem { 
        //work item
    }
    
    DispatchQueue.global().async(execute: workItem)
    

    GCD Timer

    let myQueueTimer = DispatchQueue(label: "myQueueTimer", attributes: .concurrent)
    
    let myTimer = DispatchSource.makeTimerSource(queue: myQueueTimer)
    
    myTimer.scheduleRepeating(wallDeadline: DispatchWallTime.now(), interval: .seconds(1))
    myTimer.setEventHandler {
        //TODO
    }
    myTimer.resume()
    

    总结:

    Swift 3.0中,GCD更加面向对象化,增强了可读性和易用性

    相关文章

      网友评论

          本文标题:Swift 3.0 —GCD

          本文链接:https://www.haomeiwen.com/subject/yqwzkxtx.html