1、定时器相关
(a) 上一篇文章介绍了定时器相关内容,CADisplayLink 和NSTimer都是基于Runloop的定时器,但是Runloop的任务过于繁重的时候,定时器就不准了!
(b)所以,在项目中,尽量使用GCD定时器会更准确。
2、GCD定时器封装
类方法调用,但是我觉得可以封装成实例方法可能会更好一点,晚点再封装一次。 JHTimer.h文件
#import <Foundation/Foundation.h>
NS_ASSUME_NONNULL_BEGIN
//typedef (void)(^Task)(void);
@interface JHTimer : NSObject
+ (NSString *)excuteTask:(void (^)(void))task
start:(NSTimeInterval)start
interval:(NSTimeInterval)interval
isRepeats:(BOOL)isRepeats
isAsync:(BOOL)isAsync;
+ (void)cancelTimer:(NSString *)name;
+ (void)suspendTimer:(NSString *)name;
+ (void)restartTimer:(NSString *)name;
@end
NS_ASSUME_NONNULL_END
JHTimer.m文件
#import "JHTimer.h"
@implementation JHTimer
static NSMutableDictionary *timerDict;
static BOOL isStarted;
static BOOL isCanceled;
static BOOL isSuspended;
static BOOL isRestarted;
+ (void)initialize {
static dispatch_once_t onecToken;
dispatch_once(&onecToken, ^{
timerDict = [NSMutableDictionary dictionary];
isStarted = NO;
isCanceled = NO;
isSuspended = NO;
isRestarted = NO;
});
}
+ (NSString *)excuteTask:(void (^)(void))task start:(NSTimeInterval)start interval:(NSTimeInterval)interval isRepeats:(BOOL)isRepeats isAsync:(BOOL)isAsync {
if (!task) {
return nil;
}
if (timerDict.count == 1) {
return [NSString stringWithFormat:@"%zd",timerDict.count];
}
unsigned long count = timerDict.count + 1;
NSString *timerName = [NSString stringWithFormat:@"%zd",count++];
dispatch_queue_t queue = isAsync ? dispatch_get_global_queue(0, 0) : dispatch_get_main_queue();
dispatch_source_t timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
dispatch_source_set_timer(timer, dispatch_time(DISPATCH_TIME_NOW, start * NSEC_PER_SEC), interval * NSEC_PER_SEC, 0);
dispatch_source_set_event_handler(timer, ^{
task();
if (!isRepeats) {
[self __cancelTimer:timerName];
}
});
dispatch_resume(timer);
timerDict[timerName] = timer;
isStarted = YES;
isCanceled = NO;
isSuspended = NO;
isRestarted = NO;
return timerName;
}
// pass
+ (void)cancelTimer:(NSString *)name {
if ([timerDict objectForKey:name] == nil || isSuspended) {
return;
}
dispatch_cancel([timerDict objectForKey:name]);
[timerDict removeObjectForKey:name];
isStarted = NO;
isCanceled = NO;
isSuspended = NO;
isRestarted = NO;
}
// 开启状态才可以
+ (void)suspendTimer:(NSString *)name {
if ([timerDict objectForKey:name] == nil || !isStarted || isCanceled || isSuspended) {
return;
}
dispatch_suspend([timerDict objectForKey:name]);
isStarted = YES;
isCanceled = NO;
isSuspended = YES;
isRestarted = NO;
}
// suspend状态才可以
+ (void)restartTimer:(NSString *)name {
if ([timerDict objectForKey:name] == nil || !isSuspended || isRestarted || isCanceled || !isStarted) {
return;
}
dispatch_resume([timerDict objectForKey:name]);
isStarted = YES;
isCanceled = NO;
isSuspended = NO;
isRestarted = YES;
}
+ (void)__cancelTimer:(NSString *)name {
dispatch_cancel(timerDict[name]);
[timerDict removeObjectForKey:name];
}
@end
|