Swift4使用GCD實(shí)現(xiàn)計(jì)時(shí)器
開(kāi)發(fā)過(guò)程中,我們可能會(huì)經(jīng)常使用到計(jì)時(shí)器。蘋(píng)果為我們提供了Timer。但是在平時(shí)使用過(guò)程中會(huì)發(fā)現(xiàn)使用Timer會(huì)有許多的不便
1:必須保證在一個(gè)活躍的runloop,我們知道主線程的runloop是活躍的,但是在其他異步線程runloop就需要我們自己去開(kāi)啟,非常麻煩。
2:Timer的創(chuàng)建和銷毀必須在同一個(gè)線程??缇€程就操作不了
3:內(nèi)存問(wèn)題??赡苎h(huán)引用造成內(nèi)存泄露
由于存在上述問(wèn)題,我們可以采用GCD封裝來(lái)解決。
import UIKit
typealias ActionBlock = () -> ()
class MRGCDTimer: NSObject {
static let share = MRGCDTimer()
lazy var timerContainer = [String : DispatchSourceTimer]()
/// 創(chuàng)建一個(gè)名字為name的定時(shí)
///
/// - Parameters:
/// - name: 定時(shí)器的名字
/// - timeInterval: 時(shí)間間隔
/// - queue: 線程
/// - repeats: 是否重復(fù)
/// - 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的計(jì)時(shí)器
///
/// - Parameter name: 計(jì)時(shí)器的名字
func destoryTimer(withName name:String?) {
let timer = timerContainer[name!]
if timer == nil {
return
}
timerContainer.removeValue(forKey: name!)
timer?.cancel()
}
/// 檢測(cè)是否已經(jīng)存在名字為name的計(jì)時(shí)器
///
/// - Parameter name: 計(jì)時(shí)器的名字
/// - 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()
}
取消計(jì)時(shí)器
MRGCDTimer.share.destoryTimer(withName: "name")
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
Swift 3.1聊天界面鍵盤(pán)效果的實(shí)現(xiàn)詳解
這篇文章主要給大家介紹了Swift 3.1聊天界面鍵盤(pán)效果實(shí)現(xiàn)的相關(guān)資料,文中介紹的非常詳細(xì),相信對(duì)大家的學(xué)習(xí)或者工作具有一定的參考價(jià)值,需要的朋友們下面來(lái)一起看看吧。2017-04-04
Swift如何在應(yīng)用中添加圖標(biāo)更換功能的方法
本篇文章主要介紹了Swift如何在應(yīng)用中添加圖標(biāo)更換功能的方法,小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2018-02-02
通過(guò)Notification.Name看Swift是如何優(yōu)雅的解決String硬編碼
這篇文章主要給大家介紹了通過(guò)Notification.Name看Swift是如何優(yōu)雅的解決String硬編碼的相關(guān)資料,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2018-08-08
Swift之for循環(huán)的基礎(chǔ)使用學(xué)習(xí)
這篇文章主要為大家介紹了Swift之for循環(huán)的基礎(chǔ)學(xué)習(xí),有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-06-06
Swift?中?Opaque?Types學(xué)習(xí)指南
這篇文章主要為大家介紹了Swift?中?Opaque?Types學(xué)習(xí)指南,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-04-04
swift3.0鍵盤(pán)彈起遮擋輸入框問(wèn)題的解決方案
這篇文章主要介紹了swift3.0鍵盤(pán)彈起遮擋輸入框問(wèn)題的解決方案,非常不錯(cuò),具有參考借鑒價(jià)值,需要的朋友可以參考下2016-11-11

