swift - 封裝 GCDTimer 和 NSTimer

來源:互聯網
上載者:User

標籤:source   ISE   lld   over   tin   class   nsobject   schedule   UNC   




封裝的類代碼

import 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")    }//    /// 設定定時器//    func initilAndStartTimer(timeInterval: TimeInterval,handleBlock:@escaping (() -> Void)) {//        self.timer = Timer.scheduledTimer(withTimeInterval: timeInterval, repeats: true, block: { t in//            handleBlock()//        })//    }//    /// 暫停或者重啟定時器定時器//    func stopOrStartTimer(isStop: Bool) {//        self.timer?.fireDate = isStop == true ? Date.distantFuture : Date.distantPast//    }//    /// 銷毀定時器//    func invaliTimer() {//        self.timer?.invalidate()//        self.timer = nil//    }}/// GCD定時器相關方法extension ZDTimerTool{    /// 初始化得到GCD定時器    func DispatchTimer(delayTime: Double = 0 , 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()                }            }        }else{            self.GCDTimer?.setEventHandler{                DispatchQueue.main.async {                    handleBlock()                }            }        }        self.GCDTimer?.schedule(deadline: DispatchTime.now(), repeating: timeInterval)        //        self.GCDTimer?.schedule(wallDeadline: DispatchWallTime.now(), repeating: timeInterval)        DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + delayTime) { [weak self] in            self?.GCDTimer?.resume()        }            }    /// 暫停或者重啟GCDTimer    func stopOrResumeGCDTimer(isStop: Bool){        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    }}


使用方法:

屬性 timer 和時間    //倒計時    var countdownTimer = ZDTimerTool()    // remainingSeconds代表當前倒計時剩餘的秒數    var remainingSeconds: Int = 60
//在需要的地方開啟倒計時 countdownTimer.DispatchTimer(timeInterval: 1) { [weak self] in self?.handTimer() } func handTimer() { self.remainingSeconds -= 1 if self.remainingSeconds == 0{//倒計時0秒 self.remainingSeconds = 60 self.sendButton.setTitle("重新發送", for: .normal) self.sendButton.backgroundColor = UIColor.red self.sendButton.isEnabled = true self.countdownTimer.stopOrResumeGCDTimer(isStop: true) }else{ sendButton.setTitle("\(remainingSeconds)秒後重新擷取", for: .normal) self.sendButton.backgroundColor = UIColor.gray sendButton.isEnabled = false } }

 

swift - 封裝 GCDTimer 和 NSTimer

相關文章

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.