1.NSTime
NSTime有2中常见的初始化方式,
第一种是
self.timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(printCount) userInfo:nil repeats:YES];
这种初始化方式会对当前控制器强引用,所以在离开页面的时候一定要执行[self.timer invalidate];不然当前的Controller并不会销毁。(注:如果使用的是block的方法,Controller会销毁掉,但是定时器并不会销毁,而是一直在运行,所以也需要手动暂停)。
第二种方式是:
self.timer = [NSTimer timerWithTimeInterval:1 target:self selector:@selector(printCount) userInfo:nil repeats:YES];
[[NSRunLoop mainRunLoop]addTimer:self.timer forMode:NSDefaultRunLoopMode];
此种方式必须手动添加到runloop中才能执行,退出页面时也要调用[self.timer invalidate];不然当前的Controller并不会销毁。
CADisplayLink
self.displayLink = [CADisplayLink displayLinkWithTarget:self selector:@selector(printCount)];
[self.displayLink addToRunLoop:[NSRunLoop mainRunLoop] forMode:NSDefaultRunLoopMode];
这个好像项目中基本不用。。。 http://www.jianshu.com/p/c35a81c3b9eb 可以看看这个。
GCD
NSTimeInterval period = 1.0; //设置时间间隔
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
_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, ^{
//在这里执行事件[
[self printCount];
});
dispatch_resume(_timer);
- (void)viewWillDisappear:(BOOL)animated
{
[super viewWillDisappear:animated];
dispatch_cancel(_timer);
_timer =nil;
}
GCD定时器可以不受runloop影响 比NSTimer更准确