码迷,mamicode.com
首页 > 编程语言 > 详细

swift - 添加定时器

时间:2018-11-22 21:02:00      阅读:503      评论:0      收藏:0      [点我收藏+]

标签:arp   int   message   timers   interval   sha   now()   swift   eating   



mport UIKit

/// 控制定时器的类
class ZDTimerTool: NSObject {
    /// 定时器
//    private var timer: Timer?
    /// GCD定时器
    private var GCDTimer: DispatchSourceTimer?
    /// GCD定时器的挂起状态
    private var isSuspend: Bool = false
    override init() {
        super.init()
    }
    deinit {
        // 对象在销毁前会销毁定时器,所以使用定时器应该设置全局的属性
//        self.invaliTimer()
        self.invaliGCDTimer()
        DDLOG(message: "deinit: ZDTimerTool")
    }
}
/// GCD定时器相关方法
extension ZDTimerTool{
    /// 初始化得到GCD定时器
    func DispatchTimer(timeInterval: TimeInterval , handleBlock:@escaping (() -> Void)) {
        if self.GCDTimer == nil {
            self.GCDTimer = DispatchSource.makeTimerSource(flags: [], queue: DispatchQueue.main)
            self.GCDTimer?.schedule(deadline: DispatchTime.now(), repeating: timeInterval)
            self.GCDTimer?.setEventHandler{
                DispatchQueue.main.async {
                    handleBlock()
                }
            }
            self.GCDTimer?.resume()
            self.GCDTimer?.schedule(deadline: DispatchTime.now(), repeating: timeInterval)
        }else{
            self.stopOrResumeGCDTimer(isStop: false)
        }
        
        
        
    }
    /// 暂停或者重启GCDTimer
    func stopOrResumeGCDTimer(isStop: Bool){
        guard self.isSuspend != isStop else {
            return
        }
        isStop == true ? self.GCDTimer?.suspend() : self.GCDTimer?.resume()
        self.isSuspend = isStop
    }
    /// 销毁GCD定时器
    func invaliGCDTimer() {
        if self.isSuspend == true {
            self.GCDTimer?.resume()
        }
        self.GCDTimer?.cancel() //销毁前不能为suspend(挂起状态)
        self.GCDTimer = nil
    }
}

  

2.使用

swift - 添加定时器

标签:arp   int   message   timers   interval   sha   now()   swift   eating   

原文地址:https://www.cnblogs.com/qingzZ/p/10003279.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!