前言:計(jì)時(shí)器通常用在倒計(jì)時(shí)(發(fā)送驗(yàn)證碼 60s 倒計(jì)時(shí)呢蛤,活動(dòng)倒計(jì)時(shí))惶傻、動(dòng)畫(huà)(隔 1s滾動(dòng))等,通常我們會(huì)用的是 NSTimer顾稀、GCD达罗、還有不常用的 CADisplayLink
本文不去對(duì)每種計(jì)時(shí)器做過(guò)多的介紹,主要介紹怎么在項(xiàng)目中更好更方便的使用計(jì)時(shí)器
初學(xué) iOS 的時(shí)候静秆,當(dāng)遇到登錄頁(yè)面發(fā)送驗(yàn)證碼按鈕倒計(jì)時(shí)操作粮揉,我會(huì)在當(dāng)前控制器使用 NSTimer去處理,把關(guān)于計(jì)時(shí)器倒計(jì)時(shí)模塊的代碼梳理一下記錄一下抚笔,等下次用的時(shí)候直接copy到對(duì)應(yīng)的位置
倒計(jì)時(shí)按鈕
上面就是 2016 年的時(shí)候記錄的一篇文章扶认,其實(shí)使用著并沒(méi)有什么不對(duì),只是現(xiàn)在看來(lái)殊橙,這樣寫(xiě)很 low辐宾,如果好幾個(gè)頁(yè)面都用到了計(jì)時(shí)器,那么我們?cè)诿總€(gè)頁(yè)面都要?jiǎng)?chuàng)建 NStimer膨蛮,有沒(méi)有可能整個(gè)項(xiàng)目只用一個(gè)計(jì)時(shí)器叠纹、以下有兩種方案:
1、GCD 創(chuàng)建計(jì)時(shí)器
2敞葛、項(xiàng)目全局創(chuàng)建一個(gè)計(jì)時(shí)器管理器 TimerManager
GCD方案
在工具類(lèi)中寫(xiě)下面??方法誉察,對(duì)外暴露接口
/**
倒計(jì)時(shí)
@param allSecond 總秒數(shù)
@param perSecond 每秒回調(diào)
@param end 結(jié)束回調(diào)
*/
+ (void)countDownWithAllSecond:(NSInteger)allSecond perSecond:(void(^)(NSInteger second))perSecond end:(void(^)(void))end {
if (allSecond == 0) {
return;
}
__block NSInteger timeout = allSecond;
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_source_t timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0,queue);
dispatch_source_set_timer(timer,dispatch_walltime(NULL, 0),1.0 * NSEC_PER_SEC, 0);
dispatch_source_set_event_handler(timer, ^{
if(timeout <= 0){
dispatch_source_cancel(timer);
dispatch_async(dispatch_get_main_queue(), ^{
if (end) {
end();
}
});
} else {
dispatch_async(dispatch_get_main_queue(), ^{
if (perSecond) {
perSecond(timeout);
}
timeout --;
});
}
});
dispatch_resume(timer);
}
外部調(diào)用:
sender.userInteractionEnabled = NO;
[CommenMethods countDownWithAllSecond:60 perSecond:^(NSInteger second) {
[sender setTitle:FORMAT(@"%zds",second) forState:0];
} end:^{
sender.userInteractionEnabled = YES;
[sender setTitle:@"獲取驗(yàn)證碼" forState:0];
}];
好處:GCD 計(jì)時(shí)器因?yàn)椴灰栏絉unloop,所以比 NSTimer 精準(zhǔn)惹谐,放在工具類(lèi)種供全局調(diào)用持偏,不過(guò)這么做驼卖,如果一個(gè)頁(yè)面同時(shí)多次調(diào)用該方法,也是創(chuàng)建了多個(gè)計(jì)時(shí)器
下面的方案鸿秆,全局只有一個(gè)計(jì)時(shí)器
自定義一個(gè)TimerManager管理
先說(shuō)原理:自定義一個(gè)繼承與 NSobject 的 TimerManager類(lèi)(用單例模式酌畜,全局使用一個(gè)實(shí)例對(duì)象)。
內(nèi)部放一個(gè)計(jì)時(shí)器卿叽,一個(gè)任務(wù)數(shù)組桥胞,當(dāng)數(shù)組中有任務(wù)時(shí),計(jì)時(shí)器開(kāi)始計(jì)時(shí)附帽,計(jì)時(shí)器每間隔 1s(頻率自己可以定埠戳,根據(jù)屏幕的刷新幀率井誉,最快也就 1/60秒 了)蕉扮,去遍歷任務(wù)數(shù)組,執(zhí)行任務(wù)(其實(shí)就是一個(gè) model)的 回調(diào)函數(shù)颗圣,這樣就可以每秒在外部收到消息喳钟,達(dá)到計(jì)時(shí)的效果。
當(dāng)一個(gè)任務(wù)的計(jì)時(shí)結(jié)束后在岂,從數(shù)組中移除奔则,當(dāng)所有任務(wù)都移除了,那么計(jì)時(shí)器關(guān)閉滯空[self.timer invalidate];
self.timer = nil;
蔽午,不占用內(nèi)存易茬,當(dāng)有新任務(wù)進(jìn)入時(shí),再開(kāi)啟if (!self.timer) { [self.timer fireDate]; }
代碼如下:
任務(wù)類(lèi):
#import <Foundation/Foundation.h>
NS_ASSUME_NONNULL_BEGIN
@interface Task : NSObject
///任務(wù)的唯一標(biāo)識(shí)
@property (nonatomic,readonly,copy) NSString *UUIDStr;
///以下四個(gè)屬性不需要自己去調(diào)用使用及老,供工具管理類(lèi)去使用的
///倒計(jì)時(shí)總時(shí)長(zhǎng)(單位為秒s)
@property (nonatomic,assign) NSInteger timeI;
///計(jì)時(shí)處理
@property (nonatomic,assign) NSInteger marktimeI;
///計(jì)時(shí)結(jié)束回調(diào)
@property (nonatomic,copy) void(^event)(void);
///每秒回調(diào)
@property (nonatomic,copy) void(^inTime)(NSInteger);
/// 初始化方法
/// - Parameters:
/// - timerI: 倒計(jì)時(shí)總時(shí)長(zhǎng)(單位為秒s)
/// - inTime: 每秒回調(diào)
/// - handle: 計(jì)時(shí)結(jié)束回調(diào)
- (instancetype)initWithTimeI:(NSInteger )timerI inTime:(void(^)(NSInteger))inTime handle:(void(^)(void))handle;
@end
NS_ASSUME_NONNULL_END
#import "Task.h"
@interface Task()
///外部只可讀抽莱,內(nèi)部可寫(xiě)
@property (nonatomic,copy) NSString *UUIDStr;
@end
@implementation Task
- (instancetype)initWithTimeI:(NSInteger )timerI inTime:(void(^)(NSInteger))inTime handle:(void(^)(void))handle {
if (self = [super init]) {
self.event = handle;
self.timeI = timerI;
self.marktimeI = timerI;
self.inTime = inTime;
self.UUIDStr = [[NSUUID UUID] UUIDString];
NSLog(@"%@",self.UUIDStr);
}
return self;
}
@end
管理類(lèi)
#import <Foundation/Foundation.h>
@class Task;
@interface TimerManager : NSObject
///初始化
+ (instancetype)shareInstance;
///加入任務(wù),開(kāi)始倒計(jì)時(shí)
- (void)runTask:(Task *)task;
///取消倒計(jì)時(shí)任務(wù)
- (void)cancelTask:(Task *)task;
///取消全部計(jì)時(shí)任務(wù)
- (void)cancelAllTask;
@end
#import "TimerManager.h"
#import "Task.h"
@interface TimerManager()
@property (nonatomic,strong) NSTimer *timer;
@property (nonatomic,strong) NSMutableArray *taskList;
@end
@implementation TimerManager
+ (instancetype)shareInstance{
static dispatch_once_t onceToken;
static TimerManager *manager = nil;
dispatch_once(&onceToken, ^{
if (!manager) {
manager = [[TimerManager alloc] init];
}
});
return manager;
}
- (instancetype)init{
self = [super init];
if (self) {
[[NSRunLoop mainRunLoop] addTimer:self.timer forMode:NSRunLoopCommonModes];
}
return self;
}
- (void)runTask:(Task *)task{
for (Task *t in self.taskList) {
if ([t.UUIDStr isEqualToString:task.UUIDStr]) {
return;
}
}
[self.taskList addObject:task];
if (!self.timer) {
[self.timer fireDate];
}
}
- (void)cancelTask:(Task *)task {
for (Task *t in self.taskList) {
if (t == task) {
[self.taskList removeObject:task];
if (self.taskList.count == 0) {
[self.timer invalidate];
self.timer = nil;
}
}
}
}
- (void)cancelAllTask {
[self.taskList removeAllObjects];
[self.timer invalidate];
self.timer = nil;
}
- (NSTimer *)timer{
if (!_timer) {
static NSInteger index = 0;
_timer = [NSTimer scheduledTimerWithTimeInterval:1/60.0 repeats:YES block:^(NSTimer * _Nonnull timer) {
if (index == 59) {
NSMutableArray *arr = self.taskList.mutableCopy;
for (Task *t in self.taskList) {
if (t.marktimeI < 0) {
[arr removeObject:t];
if (arr.count == 0) {
[self.timer invalidate];
self.timer = nil;
}
}
}
self.taskList = arr;
[self.taskList enumerateObjectsUsingBlock:^(Task *task, NSUInteger idx, BOOL * _Nonnull stop) {
if (task.marktimeI <= 0) {
task.event();
}else{
task.inTime(task.marktimeI);
}
task.marktimeI -= 1;
}];
index = 0;
}
index ++;
}];
}
return _timer;
}
- (NSMutableArray *)taskList {
if (!_taskList){
_taskList = [NSMutableArray array];
}
return _taskList;
}
@end
使用方法:
//添加一個(gè)任務(wù)骄恶,倒計(jì)時(shí) 30s
[TimerManager.shareInstance runTask:[[Task alloc] initWithTimeI:30 inTime:^(NSInteger time) {
NSLog(@"%zd",time);
} handle:^{
NSLog(@"好的??");
}]];
//移除一個(gè)任務(wù) t為你想取消的計(jì)時(shí)任務(wù)
[TimerManager.shareInstance cancelTask:t];
//移除所有任務(wù)食铐,計(jì)時(shí)器自動(dòng)銷(xiāo)毀
[TimerManager.shareInstance cancelAllTask];
可以把這種方案做成了靜態(tài)庫(kù)使用
以上就是所有內(nèi)容,如有好的想法僧鲁,不吝賜教