iOS计时器使用方案

2023-08-24  本文已影响0人  江湖闹士

前言:计时器通常用在倒计时(发送验证码 60s 倒计时,活动倒计时)、动画(隔 1s滚动)等,通常我们会用的是 NSTimer、GCD、还有不常用的 CADisplayLink
本文不去对每种计时器做过多的介绍,主要介绍怎么在项目中更好更方便的使用计时器


初学 iOS 的时候,当遇到登录页面发送验证码按钮倒计时操作,我会在当前控制器使用 NSTimer去处理,把关于计时器倒计时模块的代码梳理一下记录一下,等下次用的时候直接copy到对应的位置
倒计时按钮
上面就是 2016 年的时候记录的一篇文章,其实使用着并没有什么不对,只是现在看来,这样写很 low,如果好几个页面都用到了计时器,那么我们在每个页面都要创建 NStimer,有没有可能整个项目只用一个计时器、以下有两种方案:
1、GCD 创建计时器
2、项目全局创建一个计时器管理器 TimerManager

GCD方案

在工具类中写下面👇方法,对外暴露接口

/**
 倒计时
 
 @param allSecond 总秒数
 @param perSecond 每秒回调
 @param end 结束回调
 */
+ (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);
}

外部调用:

sender.userInteractionEnabled = NO;
[CommenMethods countDownWithAllSecond:60 perSecond:^(NSInteger second) {
       [sender setTitle:FORMAT(@"%zds",second) forState:0];
} end:^{
       sender.userInteractionEnabled = YES;
       [sender setTitle:@"获取验证码" forState:0];
}];

好处:GCD 计时器因为不依附Runloop,所以比 NSTimer 精准,放在工具类种供全局调用,不过这么做,如果一个页面同时多次调用该方法,也是创建了多个计时器

下面的方案,全局只有一个计时器

自定义一个TimerManager管理

先说原理:自定义一个继承与 NSobject 的 TimerManager类(用单例模式,全局使用一个实例对象)。
内部放一个计时器,一个任务数组,当数组中有任务时,计时器开始计时,计时器每间隔 1s(频率自己可以定,根据屏幕的刷新帧率,最快也就 1/60秒 了),去遍历任务数组,执行任务(其实就是一个 model)的 回调函数,这样就可以每秒在外部收到消息,达到计时的效果。
当一个任务的计时结束后,从数组中移除,当所有任务都移除了,那么计时器关闭滞空[self.timer invalidate]; self.timer = nil;,不占用内存,当有新任务进入时,再开启if (!self.timer) { [self.timer fireDate]; }

代码如下:
任务类:

#import <Foundation/Foundation.h>

NS_ASSUME_NONNULL_BEGIN

@interface Task : NSObject

///任务的唯一标识
@property (nonatomic,readonly,copy) NSString *UUIDStr;


///以下四个属性不需要自己去调用使用,供工具管理类去使用的
///倒计时总时长(单位为秒s)
@property (nonatomic,assign) NSInteger timeI;
///计时处理
@property (nonatomic,assign) NSInteger marktimeI;
///计时结束回调
@property (nonatomic,copy) void(^event)(void);
///每秒回调
@property (nonatomic,copy) void(^inTime)(NSInteger);


/// 初始化方法
/// - Parameters:
///   - timerI: 倒计时总时长(单位为秒s)
///   - inTime: 每秒回调
///   - handle: 计时结束回调
- (instancetype)initWithTimeI:(NSInteger )timerI inTime:(void(^)(NSInteger))inTime handle:(void(^)(void))handle;
@end

NS_ASSUME_NONNULL_END
#import "Task.h"

@interface Task()
///外部只可读,内部可写
@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

管理类

#import <Foundation/Foundation.h>
@class Task;

@interface TimerManager : NSObject

///初始化
+ (instancetype)shareInstance;
///加入任务,开始倒计时
- (void)runTask:(Task *)task;
///取消倒计时任务
- (void)cancelTask:(Task *)task;
///取消全部计时任务
- (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

使用方法:

//添加一个任务,倒计时 30s
[TimerManager.shareInstance runTask:[[Task alloc] initWithTimeI:30 inTime:^(NSInteger time) {
  NSLog(@"%zd",time);
} handle:^{
  NSLog(@"好的👌");
}]];

//移除一个任务 t为你想取消的计时任务
[TimerManager.shareInstance cancelTask:t];

//移除所有任务,计时器自动销毁
[TimerManager.shareInstance cancelAllTask];

可以把这种方案做成了静态库使用

以上就是所有内容,如有好的想法,不吝赐教

上一篇下一篇

猜你喜欢

热点阅读