怎么让NSTimer精准

2019-04-26  本文已影响0人  focusHYD

在面试中经常会被问到Timer 一定是准确的么?如何让Timer达到精准?

有如下2个方法:

方法1.在主线程中进行NSTimer操作,但是将NSTimer实例加到main runloop的特定mode(模式)中。避免被复杂运算操作或者UI界面刷新所干扰。

NSTimer *timer = [NSTimer timerWithTimeInterval:2.0  target:self selector:@selector(test) userInfo:nil repeats:YES];
[[NSRunLoop currentRunLoop] addTimer:timer forMode:NSRunLoopCommonModes];

方法2.在子线程中进行NSTimer的操作,再在主线程中修改UI界面显示操作结果;

- (void)timer2 {
    NSThread *thread = [[NSThread alloc] initWithTarget:self selector:@selector(newThread) object:nil];
    [thread start];
}
- (void)newThread {
    @autoreleasepool {
    [NSTimer scheduledTimerWithTimeInterval:2.0 target:self selector:@selector(showTime) userInfo:nil repeats:YES];
    [[NSRunLoop currentRunLoop] run];
      }
}
上一篇 下一篇

猜你喜欢

热点阅读