前言
iOS开发中,经常需要使用到定时器,使用NSTimer很容易出现内存泄漏,在此简单封装GCD定时器。
作为一个开发者,有一个学习的氛围跟一个交流圈子特别重要,这是一个我的iOS交流群:812157648,不管你是小白还是大牛欢迎入驻 ,分享BAT,阿里面试题、面试经验,讨论技术, 大家一起交流学习成长!
OC版本
@interface CLGCDTimer ()
/**队列*/
@property (nonatomic, strong) dispatch_queue_t queue;
/**定时器*/
@property (nonatomic, strong) dispatch_source_t timer;
/**执行时间*/
@property (nonatomic, assign) NSTimeInterval interval;
/**延迟时间*/
@property (nonatomic, assign) NSTimeInterval delaySecs;
/**是否重复*/
@property (nonatomic, assign) BOOL repeat;
/**是否正在运行*/
@property (nonatomic, assign) BOOL isRuning;
/**响应次数*/
@property (nonatomic, assign) NSInteger actionTimes;
///名称
@property (nonatomic, copy) NSString *name;
/**响应*/
@property (nonatomic, copy) void (^action) (NSInteger actionTimes);
@end
@implementation CLGCDTimer
- (instancetype _Nonnull)initWithName:(NSString *)name
interval:(NSTimeInterval)interval
delaySecs:(NSTimeInterval)delaySecs
queue:(dispatch_queue_t _Nullable)queue
repeats:(BOOL)repeats
action:(void(^ _Nullable)(NSInteger actionTimes))action {
CLGCDTimer *timer = [self initWithInterval:interval
delaySecs:delaySecs
queue:queue
repeats:repeats
action:action];
timer.name = name;
return timer;
}
- (instancetype _Nonnull)initWithInterval:(NSTimeInterval)interval
delaySecs:(NSTimeInterval)delaySecs
queue:(dispatch_queue_t _Nullable)queue
repeats:(BOOL)repeats
action:( void(^ _Nullable)(NSInteger actionTimes))action {
if (self = [super init]) {
if (queue == nil) {
queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
}
self.interval = interval;
self.delaySecs = delaySecs;
self.repeat = repeats;
self.action = action;
self.isRuning = NO;
self.queue = dispatch_queue_create([[NSString stringWithFormat:@"CLGCDTimer.%p", self] cStringUsingEncoding:NSASCIIStringEncoding], DISPATCH_QUEUE_SERIAL);
self.timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, self.queue);
dispatch_set_target_queue(self.queue, que