封装的类代码

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 = , 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 = //在需要的地方开启倒计时
countdownTimer.DispatchTimer(timeInterval: ) { [weak self] in
self?.handTimer()
} func handTimer() {
self.remainingSeconds -=
if self.remainingSeconds == {//倒计时0秒
self.remainingSeconds =
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的更多相关文章

  1. 初识 swift 封装轮播图

    一.简介 换了一家公司.换了一个环境刚开始来公司自然不能有一丝一毫的放松,每天即使是没有什么工作也是看看这个博客.那个源码.尽量让自己更充实.慢慢的开始写几篇博客记录下自己遇到的一些问题和解决方法.其 ...

  2. 纯 Swift 封装的 SQLite 框架:SQLite.swift

    SQLite.swift 是一个使用纯 Swift 语言封装 SQLite3 的操作框架. 特性: 简单的查询和参数绑定接口 安全.自动类型数据访问 隐式提交和回滚接口 开发者友好的错误处理和调试 文 ...

  3. Swift 封装

    前言 封装主要有两大目的:一是为了我们使用数据更加方便,二是为了数据保护. 1.Swift 访问修饰符 在 Swift 语言中,访问修饰符也分为三类,分别是 private.internal.publ ...

  4. swift - 封装百度地图

    1. #import <BaiduMapAPI_Base/BMKBaseComponent.h>//引入base相关所有的头文件 #import <BaiduMapAPI_Map/B ...

  5. swift版的GCD封装

    swift版的GCD封装 说明 本人针对swift封装了GCD,包括GCDQueue,GCDGroup,GCDTimer以及GCDSemaphore,使用较为便利. 源码 https://github ...

  6. Swift 2.0 封装图片折叠效果

    文/猫爪(简书作者)原文链接:http://www.jianshu.com/p/688c491580e3著作权归作者所有,转载请联系作者获得授权,并标注“简书作者”. 用Swift封装图片折叠效果 b ...

  7. swift 自定义图片轮播视图

    Swift封装图片轮播视图: import UIKit class XHAdLoopView: UIView { private var pageControl : UIPageControl? pr ...

  8. Swift和OC相互调

    在项目中不免会有多中语言开发, 不说别的就我个人而言, 之前一直都是用 OC 写的代码, 封装很多工具类, 而苹果新出来 Swift , 现在项目在向 Swift 过渡, 或者新项目是 Swift , ...

  9. Swift & OC 混编 浅析

    转载自:http://www.infoq.com/cn/articles/wangyi-cartoon-swift-mixed-practice?utm_campaign=rightbar_v2&am ...

随机推荐

  1. pyplot 绘图与可视化

    1. 基本使用 #!/usr/bin/env python # coding=utf-8 import matplotlib.pyplot as plt from numpy.random impor ...

  2. js 下关于json的销毁和添加

    var json={a:1,b:2} 现在给json添加个c,可以这样写 json.c=3或json["c"]=3 我删除一个属性 delete json.a alert(json ...

  3. C#中char空值的几种表示方式

    C#中char空值的几种表示方式 在C#中char类型的表示方式通常是用单引号作为分隔符,而字符串是用双引号作为分隔符. 例如: 程序代码 程序代码 char a = 'a'; char b = 'b ...

  4. rsync同步web数据

    rsync远程同步web服务器的数据 实验拓扑                                            服务器A(rsync服务器)--------------服务器B( ...

  5. oracle创建表空间,表及用户

    oracle要创建表要首先创建表空间,当然默认是有表空间的.而mysql创建表时,会自动创建表空间,myisam会自动建三个文 件.MYD,.MYI,.frm.innodb呢,如果没有配置独立表空间的 ...

  6. VBA 公式中使用相对位置

    .Cells(3, 4).FormulaR1C1 = "=sum(r[-" & a & "]c[0]:r[-3]c[" & b & ...

  7. mysql启动报错 The server quit without updating PID file

    [root@uz6542 data]# /etc/init.d/mysqld startStarting MySQL... ERROR! The server quit without updatin ...

  8. Redis need tcl 8.5 or newer

    hadoop@stormspark:~/workspace/redis2.6.13/src$ make testYou need tcl 8.5 or newer in order to run th ...

  9. mysql 内存占用过多的解决方法

    以下是5.6默认的设置performance_schema_max_table_instances 12500table_definition_cache 1400table_open_cache 2 ...

  10. Functional Java 学习笔记

    Functional Java Functional Java是一个在Java语言中实现函数型编程范式的类库. 从接口上看,该类库似乎与Haskell语言关系密切,接口的方法名很多来自该语言. < ...