Swift4使用GCD實現(xiàn)計時器
開發(fā)過程中,我們可能會經(jīng)常使用到計時器。蘋果為我們提供了Timer。但是在平時使用過程中會發(fā)現(xiàn)使用Timer會有許多的不便
1:必須保證在一個活躍的runloop,我們知道主線程的runloop是活躍的,但是在其他異步線程runloop就需要我們自己去開啟,非常麻煩。
2:Timer的創(chuàng)建和銷毀必須在同一個線程??缇€程就操作不了
3:內(nèi)存問題。可能循環(huán)引用造成內(nèi)存泄露
由于存在上述問題,我們可以采用GCD封裝來解決。
import UIKit typealias ActionBlock = () -> () class MRGCDTimer: NSObject { static let share = MRGCDTimer() lazy var timerContainer = [String : DispatchSourceTimer]() /// 創(chuàng)建一個名字為name的定時 /// /// - Parameters: /// - name: 定時器的名字 /// - timeInterval: 時間間隔 /// - queue: 線程 /// - repeats: 是否重復 /// - action: 執(zhí)行的操作 func scheduledDispatchTimer(withName name:String?, timeInterval:Double, queue:DispatchQueue, repeats:Bool, action:@escaping ActionBlock ) { if name == nil { return } var timer = timerContainer[name!] if timer==nil { timer = DispatchSource.makeTimerSource(flags: [], queue: queue) timer?.resume() timerContainer[name!] = timer } timer?.schedule(deadline: .now(), repeating: timeInterval, leeway: .milliseconds(100)) timer?.setEventHandler(handler: { [weak self] in action() if repeats==false { self?.destoryTimer(withName: name!) } }) } /// 銷毀名字為name的計時器 /// /// - Parameter name: 計時器的名字 func destoryTimer(withName name:String?) { let timer = timerContainer[name!] if timer == nil { return } timerContainer.removeValue(forKey: name!) timer?.cancel() } /// 檢測是否已經(jīng)存在名字為name的計時器 /// /// - Parameter name: 計時器的名字 /// - Returns: 返回bool值 func isExistTimer(withName name:String?) -> Bool { if timerContainer[name!] != nil { return true } return false } }
使用方法
MRGCDTimer.share.scheduledDispatchTimer(withName: "name", timeInterval: 1, queue: .main, repeats: true) { //code self.updateCounter() }
取消計時器
MRGCDTimer.share.destoryTimer(withName: "name")
以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
淺析Swift中struct與class的區(qū)別(匯編角度底層分析)
這篇文章主要介紹了Swift中struct與class的區(qū)別 ,本文從匯編角度分析struct與class的區(qū)別,通過實例代碼給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2020-03-03swift實現(xiàn)顏色漸變以及轉(zhuǎn)換動畫
這篇文章主要為大家詳細介紹了swift實現(xiàn)顏色漸變以及轉(zhuǎn)換動畫,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下2022-01-01swift 3.0 正則表達式查找/替換字符的實現(xiàn)代碼
正則表達式使用單個字符串來描述、匹配一系列符合某個句法規(guī)則的字符串。本文重點給大家介紹swift 3.0 正則表達式查找/替換字符的實現(xiàn)代碼,需要的朋友參考下吧2017-08-08簡陋的swift carthage copy-frameworks 輔助腳本代碼
下面小編就為大家分享一篇簡陋的swift carthage copy-frameworks 輔助腳本代碼,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-01-01使用Swift實現(xiàn)iOS App中解析XML格式數(shù)據(jù)的教程
這篇文章主要介紹了使用Swift實現(xiàn)iOS App中解析XML格式數(shù)據(jù)的教程,講到了iOS中提供的NSXMLParser和NSXMLParserDelegate兩個API的用法,需要的朋友可以參考下2016-04-04