面试题引发的思考:
Q: 使用CADisplayLink
、NSTimer
是否准时?
CADisplayLink
、NSTimer
依赖于RunLoop,而事件响应、手势识别、界面刷新等也是依赖于RunLoop实现的。- 如果RunLoop的任务过于繁重,可能会导致
CADisplayLink
、NSTimer
不准时。
Q: 如何解决CADisplayLink
、NSTimer
不准时的问题呢?
- 使用GCD的定时器会更加准时。
1. GCD定时器使用:
// TODO: ----------------- ViewController类 -----------------
@interface ViewController ()
// 强引用保留dispatch_source_t对象
@property (nonatomic, strong) dispatch_source_t timer;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// 创建队列 - 主队类:timer在主线程执行
dispatch_queue_t queue = dispatch_get_main_queue();
// 创建队列 - 非主队列:timer在子线程执行
//dispatch_queue_t queue = dispatch_queue_create("timer", DISPATCH_QUEUE_SERIAL);
// 创建定时器
dispatch_source_t timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
// 设置时间
dispatch_source_set_timer(timer, DISPATCH_TIME_NOW, 1.0 * NSEC_PER_SEC, 0 * NSEC_PER_SEC);
// 设置回调
dispatch_source_set_event_handler(timer, ^{
NSLog(@"timer - %@", [NSThread currentThread]);
});
// 启动定时器
dispatch_resume(timer);
self.timer = timer;
}
@end
2. GCD定时器封装:
下面对GCD定时器进行封装,以适用大多数场景:
// TODO: ----------------- MYTimer.h -----------------
@interface MYTimer : NSObject
/// 创建定时器
/// @param task 任务block
/// @param start 开始时间
/// @param interval 时间间隔
/// @param repeats 是否重复
/// @param async 是否异步
+ (NSString *)executeTask:(void(^)(void))task
start:(NSTimeInterval)start
interval:(NSTimeInterval)interval
repeats:(BOOL)repeats
async:(BOOL)async;
/// 创建定时器
/// @param target <#target description#>
/// @param selector <#selector description#>
/// @param start 开始时间
/// @param interval 时间间隔
/// @param repeats 是否重复
/// @param async 是否异步
+ (NSString *)executeTask:(id)target
selector:(SEL)selector
start:(NSTimeInterval)start
interval:(NSTimeInterval)interval
repeats:(BOOL)repeats
async:(BOOL)async;
/// 取消定时器
/// @param name 任务名
+ (void)cancelTask:(NSString *)name;
@end
// TODO: ----------------- MYTimer.m -----------------
@implementation MYTimer
// 存储定时器标识
static NSMutableDictionary *timers_;
// GCD信号量解决线程同步问题
dispatch_semaphore_t semaphore_;
// 初始化
+ (void)initialize {
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
timers_ = [NSMutableDictionary dictionary];
// 创建信号量
semaphore_ = dispatch_semaphore_create(1);
});
}
+ (NSString *)executeTask:(void (^)(void))task
start:(NSTimeInterval)start
interval:(NSTimeInterval)interval
repeats:(BOOL)repeats
async:(BOOL)async
{
if (!task || start < 0 || (interval <= 0 && repeats)) return nil;
// 队列
dispatch_queue_t queue = async ? 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_NOW, interval * NSEC_PER_SEC, start * NSEC_PER_SEC);
// 等待信号量
dispatch_semaphore_wait(semaphore_, DISPATCH_TIME_FOREVER);
// 定时器的唯一标识
NSString *name = [NSString stringWithFormat:@"%zd", timers_.count];
// 将定时器存放到字典中
timers_[name] = timer;
// 发送信号量
dispatch_semaphore_signal(semaphore_);
// 设置回调
dispatch_source_set_event_handler(timer, ^{
// 执行任务
task();
if (!repeats) {
// 取消不重复的任务
[self cancelTask:name];
}
});
// 启动定时器
dispatch_resume(timer);
return name;
}
+ (NSString *)executeTask:(id)target
selector:(SEL)selector
start:(NSTimeInterval)start
interval:(NSTimeInterval)interval
repeats:(BOOL)repeats
async:(BOOL)async
{
if (!target || !selector) return nil;
return [self executeTask:^{
if ([target respondsToSelector:selector]) {
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Warc-performSelector-leaks"
[target performSelector:selector];
#pragma clang diagnostic pop
}
} start:start interval:interval repeats:repeats async:async];
}
+ (void)cancelTask:(NSString *)name {
if (name.length == 0) return;
// 等待信号量
dispatch_semaphore_wait(semaphore_, DISPATCH_TIME_FOREVER);
dispatch_source_t timer = timers_[name];
if (timer) {
dispatch_source_cancel(timer);
[timers_ removeObjectForKey:name];
}
// 发送信号量
dispatch_semaphore_signal(semaphore_);
}
@end
那么MYTimer
调用方法如下:
// TODO: ----------------- ViewController类 -----------------
@interface ViewController ()
@property (nonatomic, copy) NSString *task;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
self.task = [MYTimer executeTask:^{
NSLog(@"timer - %@", [NSThread currentThread]);
} start:2.0 interval:1.0 repeats:YES async:YES];
}
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
[MYTimer cancelTask:self.task];
}
@end