常用的时间函数的总结
1 NSTimer
启动定时器
timer = [NSTimer scheduledTimerWithTimeInterval:2 target:self selector:@selector(updateWithTimer:) userInfo:nil repeats:YES];
- (void) updateWithTimer:(NSTimer*) timer {
NSLog(@"update from timer!");
}
停止定时器
[timer invalidate];
timer = nil;
2 重复的调用某个block
@interface ViewController () {
dispatch_source_t timer;
}
@end
/ Get the queue to run the blocks on
dispatch_queue_t queue = dispatch_get_main_queue();
// Create a dispatch source, and make it into a timer that goes off every second
timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
dispatch_source_set_timer(timer, DISPATCH_TIME_NOW, 1 * NSEC_PER_SEC, 0);
// When the timer goes off, heal the player
dispatch_source_set_event_handler(timer, ^{
GivePlayerHitPoints();
});
// Dispatch sources start out paused, so start the timer by resuming it
dispatch_resume(timer);
//To cancel the timer, just set the timer variable to nil:
timer = nil; ##3 CADisplayLink
当屏幕每次重绘的时候,CADisplayLink会发送消息。
displaylink = [CADisplayLink displayLinkWithTarget:self selector:@selector(update:)];
[displaylink addToRunLoop:[NSRunLoop mainRunLoop] forMode:NSRunLoopCommonModes];
-(void) update:(CADisplayLink*) displaylink {
NSLog(@"update from display link") ;
}
停止CADisplayLink
[displayLink invalidate];
displayLink = nil;
暂停 CADisplayLink
displayLink.paused = YES;
44 计算时间间隔
-(void) testDiffTime {
NSDate* old = [NSDate date] ;
NSDate* now = [NSDate date] ;
NSTimeInterval timeElapsed = [now timeIntervalSinceDate:old] ;
float minutes = timeElapsed / 60.0 ;
float hours = timeElapsed / 3600.0 ;
float seconds = fmodf(timeElapsed, 60.0) ;
}
5 在将来的某一个时刻执行任务
double timeToWait = 10.0;
dispatch_time_t delayTime = dispatch_time(DISPATCH_TIME_NOW,
(int64_t)(timeToWait * NSEC_PER_SEC));
dispatch_queue_t queue = dispatch_get_main_queue();
dispatch_after(delayTime, queue,
^(void){ // Time's up. Kaboom.
ExplodeBomb();
});