有3种方式:CADisplayLink 、NSTimer、GCDmarkdown
特色:屏幕刷新时触发一次,会重复调用指定的方法。 CADisplayLink
是一个能让咱们以和屏幕刷新率同步的
频率,将特定的内容画到屏幕上的定时器类。一般状况下,按照iOS设备屏幕的刷新率60次/秒。app
CADisplayLink
以特定模式注册到runloop
后,每当屏幕显示内容刷新结束时,runloop
就会向CADisplayLink
指定的target
发送一次指定的selector
消息,即调用方法。async
self.displayLink = [CADisplayLink displayLinkWithTarget:self selector:@selector(handleDisplayLink:)];
[self.displayLink addToRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
//当把CADisplayLink对象add到runloop中后,selector就能被周期性调用
复制代码
`frameInterval`:
设置间隔多少帧`(NSInteger)`调用一次`selector`方法。默认是1,即每帧都调用一次。
`duration `:
表示两次屏幕刷新之间的时间间隔`(CFTimeInterval)`。只读属性。
注意:该属性在`target`的`selector`被首次调用之后才会被赋值。
`selector`的调用间隔时间t 计算方式是:`t = duration × frameInterval`。
复制代码
[self.displayLink invalidate];
self.displayLink = nil;
// CADisplayLink对象就会从runloop中移除,selector调用也随即中止
复制代码
iOS设备的屏幕刷新频率是固定的,CADisplayLink
在正常状况下会在每次刷新结束都被调用,精确度至关高。 一、但若是调用的定时方法比较耗时,超过了屏幕刷新周期,就会致使跳过若干次回调机会。 二、若是CPU过于繁忙,没法保证屏幕60次/秒的刷新率,就会致使跳过若干次调用回调机会。跳过次数取决CPU的忙碌程度。oop
从原理上能够看出,CADisplayLink
适合作界面的不停重绘。好比,视频播放的时候须要不停地获取下一帧用于界面渲染。atom
计时器必定要加入RunLoop
中,而且选好mode才能运行。spa
NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(dosomething:) userInfo:nil repeats:NO];
// TimeInterval:执行以前的等待时间
// repeats : 是否须要循环
复制代码
上面的建立方法建立一个计时器,并自动加入到
MainRunloop
的NSDefaultRunLoopMode
中,能够直接使用。线程
方法scheduledTimerWithTimeInterval
在哪一个线程建立,就会被加入哪一个线程的RunLoop
中就运行在哪一个线程。 本身建立的Timer,加入到哪一个线程的RunLoop
中就运行在哪一个线程。代理
建立后,target对象的计数器会加1,直到执行完毕,会自动减1,自动释放。code
一、存在延迟问题 无论是一次性的仍是周期性,timer的实际触发时间,都会与所加入的RunLoop、RunLoop Mode
有关。orm
若是所加入的
RunLoop
正在执行一个连续性的任务,timer就会被延时触发。对于重复性的timer,若是延迟超过了一个周期,则会在延时结束后马上执行,并按照以前指定的周期继续执行。
二、页面滑动时,定时器不工做
主线程的
RunLoop
里有两个预置的模式:
kCFRunLoopDefaultMode、UITrackingRunLoopMode
都是"Common"
属性。 前者是App平时所处的状态,后者是追踪滑动的状态。
当建立一个 Timer 并加到 DefaultMode
时,Timer 会获得重复回调。但若是出现页面的滑动,RunLoop
会将模式切换为 TrackingRunLoopMode
(为了避免影响滑动操做)但这时 Timer 就不会被回调。
解决: 滑动和定时器调用互不影响,将这个 Timer 加入模式为NSRunLoopCommonModes
// 建立
NSTimer *timer = [NSTimer timerWithTimeInterval:1 target:self selector:@selector(timerAction) userInfo:nil repeats:YES];
// 添加到runloop
[[NSRunLoop mainRunLoop] addTimer:timer forMode: NSRunLoopCommonModes];
复制代码
获取runloop的方法
[NSRunLoop mainRunLoop]
这个适用于主线程中 [NSRunLoop currentRunLoop]
主线程/子线程 都适用
若是是定时器任务循环执行的话,就必须手动关闭释放!
[timer invalidate];
timer = nil;
复制代码
不能在dealloc
中释放定时器。由于计时器的repeats
为YES
时,计时器会强持有self
,致使dealloc
永远不会被调用,这个类就永远没法被释放。
解决:能够在viewDidDisappear
中释放,这样当类须要被回收时,就能够正常进入dealloc
中了。
需求:先暂停,而后再某种状况下再次开启。主要是为了防止它在后台运行,暂用CPU。 好比,在页面消失的时候关闭 ,而后等页面再次打开 ,又开启定时器。
//关闭定时器
[myTimer setFireDate:[NSDate distantFuture]];
//开启定时器
[myTimer setFireDate:[NSDate distantPast]];
复制代码
执行一次
dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, 2.0 * NSEC_PER_SEC);
dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
//执行事件
});
复制代码
重复
NSTimeInterval period = 1.0; // 时间间隔
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_source_t _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
dispatch_source_set_timer(_timer, dispatch_walltime(NULL, 0), period * NSEC_PER_SEC, 0);
dispatch_source_set_event_handler(_timer, ^{
//在这里执行事件
});
dispatch_resume(_timer); // 启动
复制代码
取消定时器: dispatch_cancel( _timer);
定时器的调用,放在主线程中最优! 在
gcd dispatch_async
中执行可能会无效!
一、CADisplayLink、NSTimer
会对target
产生强引用,若是target
又对它们强引用,就会引起循环引用。 二、runloop 会对 CADisplayLink、NSTimer
产生强引用。
解决:使用weakSelf,或NSProxy(代理对象)
// 内部使用 WeakSelf, 并在视图消失前, 关闭定时器
__weak __typeof(self) weakSelf = self;
NSTimer * timer = [NSTimer timerWithTimeInterval:1 repeats:YES block:^(NSTimer * _Nonnull timer) {
NSLog(@"timer");
}];
self.timer = timer;
[[NSRunLoop currentRunLoop] addTimer:timer forMode:NSRunLoopCommonModes];
复制代码
.h
// 解决循环引用问题
@interface MyProxy : NSProxy
- (instancetype)initWithObjc:(id)objc;
+ (instancetype)proxyWithObjc:(id)objc;
.m
@interface MyProxy()
@property(nonatomic,weak) id objc;
@end
@implementation MyProxy
- (instancetype)initWithObjc:(id)objc{
self.objc = objc;
return self;
}
+ (instancetype)proxyWithObjc:(id)objc{
return [[self alloc] initWithObjc:objc];
}
- (NSMethodSignature *)methodSignatureForSelector:(SEL)aSelector {
return [self.objc methodSignatureForSelector:aSelector];
}
- (void)forwardInvocation:(NSInvocation *)invocation {
if ([self.objc respondsToSelector:invocation.selector]) {
[invocation invokeWithTarget:self.objc];
}
}
复制代码
用代理对象引用target。
NSTimer * timer = [NSTimer timerWithTimeInterval:1
target:[TimerProxy proxyWithTarget:self]
selector:@selector(test1)
userInfo:nil
repeats:YES];
self.timer = timer;
[[NSRunLoop currentRunLoop] addTimer:timer forMode:NSRunLoopCommonModes];
复制代码