Object-C定时器,封装GCD定时器的必要性!!! (二)
上一篇:Object-C定时器,封装GCD定时器的必要性!!! (一)
上一篇认识了Object-C中的几种定时器,这一篇将Dispatch定时器(GCD定时器)封装起来.
#import <Foundation/Foundation.h>
@interface DispatchTimer : NSObject
/**
创建dispatch定时器
@param timerName 定时器名称
@param interval 时间间隔
@param queue 运行的队列(默认为全局并发队列)
@param repeats 是否重复
@param action 执行的动作
*/
+ (void)scheduleDispatchTimerWithName:(NSString *)timerName
timeInterval:(double)interval
queue:(dispatch_queue_t)queue
repeats:(BOOL)repeats
action:(dispatch_block_t)action;
/**
取消dispatch定时器
@param timerName 定时器名称
*/
+ (void)cancelTimerWithName:(NSString *)timerName;
/**
取消所有创建的dispatch定时器
*/
+ (void)cancelAllTimer;
@end
#import "DispatchTimer.h"
@implementation DispatchTimer
static NSMutableDictionary * timerContainer;
+ (void)initialize
{
timerContainer = [NSMutableDictionary dictionary];
}
+ (void)scheduleDispatchTimerWithName:(NSString *)timerName timeInterval:(double)interval queue:(dispatch_queue_t)queue repeats:(BOOL)repeats action:(dispatch_block_t)action
{
if (nil == timerName) {
return;
}
if (nil == queue) {//默认为全局并发队列
queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
}
dispatch_source_t timer = [
timerContainer objectForKey:timerName];
if (nil == timer) {//创建
timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
[timerContainer setObject:timer forKey:timerName];
//执行timer 一定放在这里 放下面会造成野地址
dispatch_resume(timer);
}
dispatch_time_t start = dispatch_time(DISPATCH_TIME_NOW, interval * NSEC_PER_SEC);
dispatch_source_set_timer(timer, start, interval * NSEC_PER_SEC, 0);
__weak typeof(self) weakSelf = self;
dispatch_source_set_event_handler(timer, ^{
action();
if (!repeats) {
[weakSelf cancelTimerWithName:timerName];
}
});
}
+ (void)cancelTimerWithName:(NSString *)timerName
{
dispatch_source_t timer = [timerContainer objectForKey:timerName];
if (nil == timer) {
return;
}
[timerContainer removeObjectForKey:timerName];
dispatch_source_cancel(timer);
}
+ (void)cancelAllTimer
{
[timerContainer enumerateKeysAndObjectsUsingBlock:^(NSString * timerName, dispatch_source_t timer, BOOL * _Nonnull stop) {
[timerContainer removeObjectForKey:timerName];
dispatch_source_cancel(timer);
}];
}
@end
为了方便调用:将定时器的创建、销毁方法设计为类方法。
源码: https://github.com/lieryang/DispatchTimer 欢迎star,有动力才有成绩!!!
更多内容--> 博客导航 每周一篇哟!!!
有任何关于iOS开发的问题!欢迎下方留言!!!或者邮件lieryangios@126.com 虽然我不一定能够解答出来,但是我会请教iOS开发高手!!!解答您的问题!!!