您的位置:首页 > 其它

NSTimer 与 CADisplayLink

2015-03-12 09:50 309 查看
1.简介

1.1 调用周期:
NSTimer通过TimeInterval设置调用间隔。
CADisplayLink默认每秒运行60次(和CPU占用率有关,当CPU忙时达不到60),通过它的frameInterval属性改变每秒运行帧数,如设置为2,意味CADisplayLink两帧运行一次,有效的逻辑大概每秒运行30次。
1.2 是否重复调用:
NSTimer接受repeats参数是否重复(yes表示重复,no表示不重复)[不用scheduled的,添加到runloop中后,该定时器将在初始化时指定的timeInterval秒后自动触发。]
CADisplayLink,当被添加到runloop中后,selector就能被周期性调用,直到invalidate
1.3 使用方法:
NSTimer 的使用:
//初始化一个定时器:
-(void)initTimer
{
//定时器
self.showTimer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(handleMaxShowTimer:) userInfo:nil repeats:NO];
//或者:
self.showTimer = [NSTimer timerWithTimeInterval:3.0 target:self selector:@selector(handleMaxShowTimer:) userInfo:nil repeats:NO];
[[NSRunLoop currentRunLoop]addTimer:<span style="font-family: Arial, Helvetica, sans-serif;">self.showTimer </span>forMode:NSDefaultRunLoopMode];
}
//触发事件
-(void)handleMaxShowTimer:(NSTimer *)theTimer
{
}
- (void)stopTimer
{
[self.showTimer invalidate];
self.showTimer = nil;
}


CADisplayLink使用方法:
- (void)startDisplayLink
{
self.displayLink = [CADisplayLink displayLinkWithTarget:self
selector:@selector(handleDisplayLink:)];
[self.displayLink addToRunLoop:[NSRunLoop currentRunLoop]
forMode:NSDefaultRunLoopMode];
}

- (void)handleDisplayLink:(CADisplayLink *)displayLink
{
//do something
}
- (void)stopDisplayLink
{
[self.displayLink invalidate];
self.displayLink = nil;
}
1.4 使用场景:
NSTimer 我们通常会用在背景计算,更新一些数值资料,而如果牵涉到画面的更新,动画过程的演变,我们通常会用CADisplayLink。
二、特性
2.1 原理不同
NSTimer以指定的模式注册到runloop后,每当设定的周期时间到达后,runloop会向指定的target发送一次指定的selector消息。

CADisplayLink以特定模式注册到runloop后, 每当屏幕显示内容刷新结束的时候(如果frameInterval不是默认值,则根据设置的帧率触发),runloop就会向CADisplayLink指定的target发送一次指定的selector消息, CADisplayLink类对应的selector就会被调用一次。
2.2 周期设置方式不同

NSTimer的selector调用周期可以在初始化时直接设定,比较灵活。

CADisplayLink的调用周期和 iOS设备的屏幕刷新频率(FPS)(60Hz)相关,因此CADisplayLink的selector 默认调用周期是每秒60次,这个周期可以通过frameInterval属性设置, CADisplayLink的selector每秒调用次数=60/frameInterval(如果CPU占用率高的话可能达不到)。比如当 frameInterval设为2,每秒调用就变成30次。CADisplayLink 周期的设置方式没有NSTimer方便。
2.3 精准度
NSTimer的精准度相对CADisplayLink比较低,比如NSTimer的触发时间到的时候,runloop如果在忙于别的调用,触发时间就会推迟到下一个runloop周期。更有甚者,在OS
X v10.9以后为了尽量避免在NSTimer触发时间到了而去中断当前处理的任务,NSTimer新增了tolerance属性,让用户可以设置可以容忍的触发的时间范围[NSTimer可以精确到50-100毫秒]。

CADisplayLink的精准度和屏幕刷新频率相对应,CADisplayLink在正常情况下会在每次刷新结束都被调用,精确度相当高
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: