在iOS编程中,我们可以使用CADisplayLink,以便每次屏幕刷新时调用我们的处理程序。想法是提升游戏/动画状态,然后将其绘制到屏幕上。要获取当前时间,我们可以使用事件处理程序中的displayLink.timestamp。但是,当我在设备上运行它时,为什么它返回与之前调用处理程序相同的值?因此,我无法正确计算经过的时间,因为它将为0。
使用NSDate查找时间。在模拟器上运行。
这是相关代码。假设您从XCode创建单个视图应用程序。然后按如下所示更改视图控制器的头文件:
@interface MBIViewController : UIViewController
{
float _lastTimeStamp;
NSDate *_lastDate;
}
-(void)updateView:(CADisplayLink *)displayLink; // using displayLink.timestamp
-(void)updateView2:(CADisplayLink *)displayLink; // using NSDate
@end
然后在viewDidLoad中挂钩处理程序:
_lastTimeStamp = CACurrentMediaTime();
_lastDate = [NSDate date];
CADisplayLink *displayLink = [CADisplayLink displayLinkWithTarget:self selector:@selector(updateView:)]; // change this to updateView2: to compare
[displayLink addToRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
然后是2个处理程序:
-(void)updateView:(CADisplayLink *)displayLink
{
float newTimeStamp = displayLink.timestamp;
float elapsedTime = newTimeStamp - _lastTimeStamp;
float fps = 1.0f / elapsedTime;
_lastTimeStamp = newTimeStamp;
NSLog(@"elapsed time: %f", elapsedTime);
NSLog(@"fps: %f", fps);
NSLog(@"---");
}
-(void)updateView2:(CADisplayLink *)displayLink
{
NSDate *newDate = [NSDate date];
float elapsedTime = [newDate timeIntervalSinceDate:_lastDate];
float fps = 1.0f / elapsedTime;
_lastDate = newDate;
NSLog(@"elapsed time: %f", elapsedTime);
NSLog(@"fps: %f", fps);
NSLog(@"---");
}
以下是设备上的updateView:输出:
2013-07-06 19:07:06.274 DisplayLinkTest[24842:907] elapsed time: 0.000000
2013-07-06 19:07:06.281 DisplayLinkTest[24842:907] fps: inf
2013-07-06 19:07:06.286 DisplayLinkTest[24842:907] ---
2013-07-06 19:07:06.291 DisplayLinkTest[24842:907] elapsed time: 0.000000
2013-07-06 19:07:06.298 DisplayLinkTest[24842:907] fps: inf
2013-07-06 19:07:06.303 DisplayLinkTest[24842:907] ---
2013-07-06 19:07:06.308 DisplayLinkTest[24842:907] elapsed time: 0.000000
2013-07-06 19:07:06.315 DisplayLinkTest[24842:907] fps: inf
2013-07-06 19:07:06.321 DisplayLinkTest[24842:907] ---
2013-07-06 19:07:06.325 DisplayLinkTest[24842:907] elapsed time: 0.062500
2013-07-06 19:07:06.329 DisplayLinkTest[24842:907] fps: 16.000000
2013-07-06 19:07:06.333 DisplayLinkTest[24842:907] ---
如果它是正确的,它总是16fps。
如果你挂钩到updateView2会发生什么:相反:
2013-07-06 19:16:03.318 DisplayLinkTest[24871:907] elapsed time: 0.016677
2013-07-06 19:16:03.322 DisplayLinkTest[24871:907] fps: 59.962959
2013-07-06 19:16:03.325 DisplayLinkTest[24871:907] ---
2013-07-06 19:16:03.335 DisplayLinkTest[24871:907] elapsed time: 0.016731
2013-07-06 19:16:03.339 DisplayLinkTest[24871:907] fps: 59.769207
2013-07-06 19:16:03.342 DisplayLinkTest[24871:907] ---
2013-07-06 19:16:03.352 DisplayLinkTest[24871:907] elapsed time: 0.017200
2013-07-06 19:16:03.357 DisplayLinkTest[24871:907] fps: 58.139557
2013-07-06 19:16:03.365 DisplayLinkTest[24871:907] ---
2013-07-06 19:16:03.369 DisplayLinkTest[24871:907] elapsed time: 0.017283
2013-07-06 19:16:03.374 DisplayLinkTest[24871:907] fps: 57.860249
我是否错误地使用了displayLink.timestamp?感谢