swift版的GCD封装

简介:

swift版的GCD封装

 

说明

本人针对swift封装了GCD,包括GCDQueue,GCDGroup,GCDTimer以及GCDSemaphore,使用较为便利.

 

源码

https://github.com/YouXianMing/Swift-GCD


//
//  GCDQueue.swift
//  GCD
//
//  http://home.cnblogs.com/u/YouXianMing/
//  https://github.com/YouXianMing
//
//  Created by YouXianMing on 15/10/9.
//

import UIKit

enum QueueType {
    
    case SerialQueue,     // 串行线程队列
         ConcurrentQueue, // 并发线程队列
         None             // 无类型
}

class GCDQueue: NSObject {
        
    // MARK: 变量
    var dispatchQueue : dispatch_queue_t!
    
    // MARK: 初始化
    override init() {
        
        super.init()
        dispatchQueue = dispatch_queue_create(nil, DISPATCH_QUEUE_CONCURRENT)
    }
    
    init(queueType : QueueType) {
        
        super.init()
        
        switch queueType {
            
        case .SerialQueue:
            
            dispatchQueue = dispatch_queue_create(nil, DISPATCH_QUEUE_SERIAL)
            break
            
        case .ConcurrentQueue:
            
            dispatchQueue = dispatch_queue_create(nil, DISPATCH_QUEUE_CONCURRENT)
            break
            
        case .None:
            
            dispatchQueue = nil
            break
        }
    }
    
    // MARK: 单例
    static let mainQueue : GCDQueue = {
        
        let instance           = GCDQueue(queueType: .None)
        instance.dispatchQueue = dispatch_get_main_queue()
        
        return instance
        }()
    
    static let globalQueue : GCDQueue = {
        
        let instance           = GCDQueue(queueType: .None)
        instance.dispatchQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)
        
        return instance
        }()
    
    static let highPriorityGlobalQueue : GCDQueue = {
        
        let instance           = GCDQueue(queueType: .None)
        instance.dispatchQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0)
        
        return instance
        }()
    
    static let lowPriorityGlobalQueue : GCDQueue = {
        
        let instance           = GCDQueue(queueType: .None)
        instance.dispatchQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0)
        
        return instance
        }()
    
    static let backgroundPriorityGlobalQueue : GCDQueue = {
        
        let instance           = GCDQueue(queueType: .None)
        instance.dispatchQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0)
        
        return instance
        }()
    
    // MARK: 执行
    
    /**
    Submits a block for asynchronous execution on a dispatch queue and returns immediately.
    
    - parameter block: dispatch block
    */
    func excute(block : dispatch_block_t) {
        
        dispatch_async(dispatchQueue, block)
    }
    
    func excute(block : dispatch_block_t, afterDelayWithNanoseconds : Int64) {
        
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, afterDelayWithNanoseconds), dispatchQueue, block)
    }
    
    /**
    Submits a block object for execution on a dispatch queue and waits until that block completes.
    
    - parameter block: dispatch block
    */
    func waitExecute(block : dispatch_block_t) {
        
        dispatch_sync(dispatchQueue, block)
    }
    
    /**
    Submits a barrier block for asynchronous execution and returns immediately.
    
    - parameter block: dispatch block
    */
    func barrierExecute(block : dispatch_block_t) {
        
        dispatch_barrier_async(dispatchQueue, block)
    }
    
    /**
    Submits a barrier block object for execution and waits until that block completes.
    
    - parameter block: dispatch block
    */
    func waitBarrierExecute(block : dispatch_block_t) {
        
        dispatch_barrier_sync(dispatchQueue, block)
    }
    
    // MARK: 便利构造器方法
    class func executeInMainQueue(block : dispatch_block_t) {
    
        dispatch_async(mainQueue.dispatchQueue, block)
    }
    
    class func executeInGlobalQueue(block : dispatch_block_t) {
        
        dispatch_async(globalQueue.dispatchQueue, block)
    }
    
    class func executeInHighPriorityGlobalQueue(block : dispatch_block_t) {
        
        dispatch_async(highPriorityGlobalQueue.dispatchQueue, block)
    }
    
    class func executeInLowPriorityGlobalQueue(block : dispatch_block_t) {
        
        dispatch_async(lowPriorityGlobalQueue.dispatchQueue, block)
    }
    
    class func executeInBackgroundPriorityGlobalQueue(block : dispatch_block_t) {
        
        dispatch_async(backgroundPriorityGlobalQueue.dispatchQueue, block)
    }
    
    class func executeInMainQueue(block : dispatch_block_t, afterDelaySeconds : Double) {
        
        let delayTime : Int64 = Int64(afterDelaySeconds * Double(NSEC_PER_SEC))
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, delayTime), mainQueue.dispatchQueue, block)
    }
    
    class func executeInGlobalQueue(block : dispatch_block_t, afterDelaySeconds : Double) {
        
        let delayTime : Int64 = Int64(afterDelaySeconds * Double(NSEC_PER_SEC))
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, delayTime), globalQueue.dispatchQueue, block)
    }
    
    class func executeInHighPriorityGlobalQueue(block : dispatch_block_t, afterDelaySeconds : Double) {
        
        let delayTime : Int64 = Int64(afterDelaySeconds * Double(NSEC_PER_SEC))
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, delayTime), highPriorityGlobalQueue.dispatchQueue, block)
    }
    
    class func executeInLowPriorityGlobalQueue(block : dispatch_block_t, afterDelaySeconds : Double) {
        
        let delayTime : Int64 = Int64(afterDelaySeconds * Double(NSEC_PER_SEC))
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, delayTime), lowPriorityGlobalQueue.dispatchQueue, block)
    }
    
    class func executeInBackgroundPriorityGlobalQueue(block : dispatch_block_t, afterDelaySeconds : Double) {
        
        let delayTime : Int64 = Int64(afterDelaySeconds * Double(NSEC_PER_SEC))
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, delayTime), backgroundPriorityGlobalQueue.dispatchQueue, block)
    }
    
    // MARK: 恢复与挂起
    func suspend() {
        
        dispatch_suspend(dispatchQueue)
    }
    
    func resume() {
        
        dispatch_resume(dispatchQueue)
    }
    
    
    // MARK: GCDGroup相关
    func excute(block : dispatch_block_t, inGroup : GCDGroup!) {
        
        dispatch_group_async(inGroup.dispatchGroup, dispatchQueue, block)
    }
    
    func notify(block : dispatch_block_t, inGroup : GCDGroup!) {
        
        dispatch_group_notify(inGroup.dispatchGroup, dispatchQueue, block)
    }
}


//
//  GCDGroup.swift
//  GCD
//
//  http://home.cnblogs.com/u/YouXianMing/
//  https://github.com/YouXianMing
//
//  Created by YouXianMing on 15/10/9.
//

import UIKit

class GCDGroup: NSObject {

    // MARK: 变量
    var dispatchGroup : dispatch_group_t!
    
    // MARK: 初始化
    override init() {
        
        super.init()
        dispatchGroup = dispatch_group_create()
    }
    
    // MARK: 操作
    func enter() {
    
        dispatch_group_enter(dispatchGroup)
    }
    
    func leave() {
    
        dispatch_group_leave(dispatchGroup)
    }
    
    func wait() {
    
        dispatch_group_wait(dispatchGroup, DISPATCH_TIME_FOREVER)
    }
    
    func waitWithNanoseconds(nanoseconds : Int64) -> Bool {
    
        return dispatch_group_wait(dispatchGroup, dispatch_time(DISPATCH_TIME_NOW, nanoseconds)) == 0
    }
}


//
//  GCDTimer.swift
//  GCD
//
//  http://home.cnblogs.com/u/YouXianMing/
//  https://github.com/YouXianMing
//
//  Created by YouXianMing on 15/10/9.
//

import UIKit

class GCDTimer: NSObject {

    // MARK: 变量
    var dispatchSource : dispatch_source_t!
    
    // MARK: 初始化
    override init() {
        
        super.init()
        dispatchSource = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0))
    }
    
    init(inQueue : GCDQueue) {
        
        super.init()
        self.dispatchSource = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, inQueue.dispatchQueue)
    }
    
    // MARK: 执行
    func event(block : dispatch_block_t, timeIntervalWithNanoseconds : UInt64) {
    
        dispatch_source_set_timer(dispatchSource, dispatch_time(DISPATCH_TIME_NOW, 0), timeIntervalWithNanoseconds, 0)
        
        dispatch_source_set_event_handler(dispatchSource) { () -> Void in
            
            block()
        }
    }
    
    func event(block : dispatch_block_t, timeIntervalWithSeconds : Double) {
        
        let timeInterval : UInt64 = UInt64(timeIntervalWithSeconds * Double(NSEC_PER_SEC))
        dispatch_source_set_timer(dispatchSource, dispatch_time(DISPATCH_TIME_NOW, 0), timeInterval, 0)
        dispatch_source_set_event_handler(dispatchSource) { () -> Void in
            
            block()
        }
    }
    
    func start() {
    
        dispatch_resume(dispatchSource)
    }
    
    func destroy() {
    
        dispatch_source_cancel(dispatchSource)
    }
}


//
//  GCDSemaphore.swift
//  GCD
//
//  http://home.cnblogs.com/u/YouXianMing/
//  https://github.com/YouXianMing
//
//  Created by YouXianMing on 15/10/9.
//

import UIKit

class GCDSemaphore: NSObject {

    // MARK: 变量
    var dispatchSemaphore : dispatch_semaphore_t!
    
    // MARK: 初始化
    override init() {
        
        super.init()
        dispatchSemaphore = dispatch_semaphore_create(0)
    }
    
    init(withValue : Int) {
        
        super.init()
        dispatchSemaphore = dispatch_semaphore_create(withValue)
    }
    
    // 执行
    func signal() -> Bool {
    
        return dispatch_semaphore_signal(dispatchSemaphore) != 0
    }
    
    func wait() {
    
        dispatch_semaphore_wait(dispatchSemaphore, DISPATCH_TIME_FOREVER)
    }
    
    func wait(withNanoseconds : Int64) -> Bool {
    
        return dispatch_semaphore_wait(dispatchSemaphore, dispatch_time(DISPATCH_TIME_NOW, withNanoseconds)) == 0
    }
}


//
//  ViewController.swift
//  GCD
//
//  Created by YouXianMing on 15/10/9.
//  Copyright © 2015年 YouXianMing. All rights reserved.
//

import UIKit

class ViewController: UIViewController {
    
    var queue     : GCDQueue!
    var group     : GCDGroup!
    var timer     : GCDTimer!
    var semaphore : GCDSemaphore!
    
    override func viewDidLoad() {
        
        super.viewDidLoad()
        
        timerUse()
    }
    
    // MARK: 各种用法
    
    /**
    普通用法
    */
    func normalUse() {
        
        GCDQueue.globalQueue.excute { () -> Void in
            
            // 子线程执行操作
            
            GCDQueue.mainQueue.excute({ () -> Void in
                
                // 主线程更新UI
            })
        }
        
        
        GCDQueue.executeInGlobalQueue { () -> Void in
            
            // 子线程执行操作
            
            GCDQueue.executeInMainQueue({ () -> Void in
                
                // 主线程更新UI
            })
        }
    }
    
    /**
    延时用法
    */
    func delayUse() {
        
        GCDQueue.executeInGlobalQueue({ () -> Void in
            
            // 延时 2s 执行
            
            }, afterDelaySeconds: 2)
    }
    
    func waitExecute() {
        
        queue = GCDQueue(queueType: .ConcurrentQueue)
        
        queue.waitExecute { () -> Void in
            
            print("1")
            sleep(1)
        }
        
        queue.waitExecute { () -> Void in
            
            print("2")
            sleep(1)
        }
        
        queue.waitExecute { () -> Void in
            
            print("3")
            sleep(1)
        }
        
        queue.waitExecute { () -> Void in
            
            print("4")
        }
    }
    
    /**
    设置屏障
    */
    func barrierExecute() {
        
        queue = GCDQueue(queueType: .ConcurrentQueue)
        
        queue.excute { () -> Void in
            
            print("1")
        }
        
        queue.excute { () -> Void in
            
            print("2")
        }
        
        queue.excute { () -> Void in
            
            print("3")
            sleep(1)
        }
        
        queue.barrierExecute { () -> Void in
            
            print("barrierExecute")
        }
        
        queue.excute { () -> Void in
            
            print("4")
        }
        
        queue.excute { () -> Void in
            
            print("5")
        }
        
        queue.excute { () -> Void in
            
            print("6")
        }
    }
    
    /**
    GCDGroup的使用
    */
    func groupUse() {
        
        group = GCDGroup()
        queue = GCDQueue()
        
        queue.excute({ () -> Void in
            
            print("1")
            
            }, inGroup: group)
        
        queue.excute({ () -> Void in
            
            print("2")
            
            }, inGroup: group)
        
        queue.excute({ () -> Void in
            
            print("3")
            
            }, inGroup: group)
        
        queue.excute({ () -> Void in
            
            print("4")
            
            }, inGroup: group)
        
        queue.excute({ () -> Void in
            
            print("5")
            
            }, inGroup: group)
        
        queue.excute({ () -> Void in
            
            print("6")
            
            }, inGroup: group)
        
        queue.excute({ () -> Void in
            
            print("7")
            
            }, inGroup: group)
        
        queue.excute({ () -> Void in
            
            print("8")
            
            }, inGroup: group)
        
        queue.notify({ () -> Void in
            
            print("都完成了")
            
            }, inGroup: group)
    }
    
    /**
    GCDTimer的使用
    */
    func timerUse() {
        
        timer = GCDTimer(inQueue: GCDQueue.globalQueue)
        timer.event({ () -> Void in
            
            print("timer event")
            
            }, timeIntervalWithSeconds: 1)
        timer.start()
    }
    
    /**
    GCD信号量的使用
    */
    func semaphoreUse() {
        
        semaphore = GCDSemaphore()
        queue     = GCDQueue(queueType: .ConcurrentQueue)
        
        queue.excute { () -> Void in
            
            print("1")
            self.semaphore.signal()
        }
        
        queue.excute { () -> Void in
            
            print("2")
            self.semaphore.signal()
        }
        
        queue.excute { () -> Void in
            
            print("3")
            self.semaphore.signal()
        }
        
        queue.excute { () -> Void in
            
            print("4")
            self.semaphore.signal()
        }
        
        queue.excute { () -> Void in
            
            self.semaphore.wait()
            self.semaphore.wait()
            self.semaphore.wait()
            self.semaphore.wait()
            
            print("都完成了")
        }
    }
}

细节


目录
相关文章
|
3月前
|
API Swift C语言
探索iOS开发:Swift中的异步编程与GCD应用
【8月更文挑战第4天】在iOS开发的海洋中,掌握Swift语言的航向是至关重要的。本文将引领你深入理解Swift中的异步编程概念,并借助Grand Central Dispatch(GCD)这一强大的工具,来简化并发编程的复杂性。我们将通过实际代码示例,展现如何在iOS应用中高效地管理后台任务和提升用户界面的响应性。
78 3
|
网络性能优化 API 调度
36 Swift多线程编程新思路:GCD
Swift多线程编程新思路:GCD
104 0
|
Swift
Swift - 自定义tabbar的封装
Swift - 自定义tabbar的封装
337 0
Swift - 自定义tabbar的封装
|
Swift
swift微博第7天(导航条按钮的封装)
swift微博第7天(导航条按钮的封装)
139 0
swift微博第7天(导航条按钮的封装)
|
iOS开发
swift4.0 评论弹出键盘的封装
demo地址: https://github.com/weiman152/SwiftCustomInputView 很多应用都有评论功能,评论功能涉及到的问题主要就是两个: 1.键盘弹出的高度 2.动态改变textview的高度 剩下的就是一些动画了。
1089 0
|
JSON Go 数据格式
Swift 3.0封装 URLSession 的GET/SET方法代替 Alamofire
升级到 Swift3.0 之后,新版本的 Alamofire 只支持 iOS 9.0 以上的系统,如果要适配 iOS 8,需要自己封装 URLSession,下面是笔者的方案: 这里使用的是 Swift 自己的原生类型 URLSession,而不是NSURLSession。
941 0
|
JSON 数据格式 iOS开发
Swift学习第十枪-AFNetwoking3.0的封装
版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u010046908/article/details/51588829 下面是我的新建的Swift学习交流群,欢迎大家一起来共同学习Swift。
829 0