参考了iOS定时器,你真的会使用吗?
- NSTimer
- 必须加入到Runloop中
- 受Runloop影响,存在延时
- 受Runloop的Mode的影响,如添加到了NSDefaultRunLoopMode模式,滑动的时候mode切换为UITrackingRunLoopMode,定时器会暂停执行
- dispatch_after, dispatch source timer
- 不受Runloop的影响,精度很高
- handler代码在子线程
- 注意
dispatch_walltime
可以让计时器按照真实时间间隔进行计时
- 创建的timer一定要有
dispatch_suspend
或dispatch_source_cancel
否则定时器将不执行
- CADisplayLink
- 必须添加到runloop
- 和屏幕刷新率同步的定时器
- 适合做界面的不停重绘,比如视频播放的时候需要不停地获取下一帧用于界面渲染,或者做动画
example:
- NSTimer
-(void)createNSTimerAndFire
{
NSMutableDictionary *dic = @{@"count":@10}.mutableCopy;
NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(runTimer:) userInfo:dic repeats:YES];
[timer fire];
}
-(void)createNSTimerAndAddToRunloop
{
NSMutableDictionary *dic = @{@"count":@10}.mutableCopy;
NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(runTimer:) userInfo:dic repeats:YES];
[[NSRunLoop currentRunLoop] addTimer:timer forMode:NSRunLoopCommonModes];
}
- (void)runTimer:(NSTimer *)timer
{
NSLog(@"timer = %@, userInfo = %@",timer,timer.userInfo);
NSMutableDictionary *dic = timer.userInfo;
NSNumber *count = dic[@"count"];
if (count.integerValue <= 0) {
[timer invalidate];
return;
}
dic[@"count"] = @(count.integerValue-1);
}
- GCD
- (void)dispatch_delay {
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
//do stomething after 3.0secs
});
}
- (void)createDispatchTimer
{
__block int count = 10;
dispatch_source_t timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, dispatch_get_main_queue());
dispatch_source_set_timer(timer, DISPATCH_TIME_NOW, 1.0 * NSEC_PER_SEC, 0 * NSEC_PER_SEC);
dispatch_source_set_event_handler(timer, ^{
count--;
NSLog(@"count--%d",count);
if (count <= 0) {
dispatch_async(dispatch_get_main_queue(), ^{
//do something in the main thread
});
// time out, cancel timer
dispatch_source_cancel(timer);
}
});
dispatch_resume(timer);
}
- CADisplayLink
- (void)createDisplayLink {
CADisplayLink *link = [CADisplayLink displayLinkWithTarget:self selector:@selector(displayLinkHandler:)];
link.frameInterval = 1;
//ios10.0以后使用 preferredFramesPerSecond
[link addToRunLoop:[NSRunLoop currentRunLoop] forMode:NSRunLoopCommonModes];
}
- (void)displayLinkHandler:(CADisplayLink *)sender
{
NSLog(@"sender = %@",sender);
[sender invalidate];
}