这篇文章主要为大家详细介绍了Swift4使用GCD实现计时器,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
开发过程中,我们可能会经常使用到计时器。苹果为我们提供了Timer。但是在平时使用过程中会发现使用Timer会有许多的不便
1:必须保证在一个活跃的runloop,我们知道主线程的runloop是活跃的,但是在其他异步线程runloop就需要我们自己去开启,非常麻烦。
2:Timer的创建和销毁必须在同一个线程。跨线程就操作不了
3:内存问题。可能循环引用造成内存泄露
由于存在上述问题,我们可以采用GCD封装来解决。
import UIKit
typealias ActionBlock = () -> ()
class MRGCDTimer: NSObject {
static let share = MRGCDTimer()
lazy var timerContainer = [String : DispatchSourceTimer]()
/// 创建一个名字为name的定时
///
/// - Parameters:
/// - name: 定时器的名字
/// - timeInterval: 时间间隔
/// - queue: 线程
/// - repeats: 是否重复
/// - action: 执行的操作
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()
}
/// 检测是否已经存在名字为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")
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持编程学习网。
织梦狗教程
本文标题为:Swift4使用GCD实现计时器


基础教程推荐
猜你喜欢
- R语言绘制折线图实例分析 2022-11-21
- Swift中重写和重载的使用与对比总结 2023-07-05
- win10下使用virtualbox + vagrant配置ruby开发机环境 2023-07-23
- R语言-修改(替换)因子变量的元素操作 2022-11-26
- R语言 ggplot2改变柱状图的顺序操作 2022-11-17
- ruby-on-rails-为使用Rails 4,nginx和乘客的用户设置自定义域 2023-09-21
- Swift初始化器与可选链的使用方法介绍 2023-07-08
- Ruby3多线程并行Ractor使用方法详解 2023-07-23
- 浅析ELF转二进制允许把 Binary 文件加载到任意位置 2023-07-06
- ruby on rails validates 2023-09-22