美文网首页
NStimer计时器值得注意的点

NStimer计时器值得注意的点

作者: 就叫醍醐灌顶吧 | 来源:发表于2018-03-06 10:23 被阅读0次

    在使用NStimer的时候,有时候会发现计时的不太准确主要是因为NSTimer加在main runloop中,模式是NSDefaultRunLoopMode,main负责所有主线程事件,例如UI界面的操作,复杂的运算,这样在同一个runloop中timer就会产生阻塞。另外一个就是模式的改变。主线程的 RunLoop 里有两个预置的 Mode:kCFRunLoopDefaultMode 和 UITrackingRunLoopMode。当你创建一个 Timer 并加到 DefaultMode 时,Timer 会得到重复回调,但此时滑动一个ScrollView时,RunLoop 会将 mode 切换为 TrackingRunLoopMode,这时 Timer 就不会被回调,并且也不会影响到滑动操作。所以就会影响到NSTimer不准的情况。

    PS:DefaultMode 是 App 平时所处的状态,rackingRunLoopMode 是追踪 ScrollView 滑动时的状态。

    解决方法:

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

    self.timer = [NSTimer timerWithTimeInterval:1 target:self selector:@selector(showTime) userInfo:nil repeats:YES];

    [[NSRunLoop currentRunLoop] addTimer:self.timer forMode:NSRunLoopCommonModes];

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

    - (void)timer {

    NSThread *thread = [[NSThread alloc] initWithTarget:self selector:@selector(newThread) object:nil];

    [thread start];

    }

    - (void)newThread

    {

    @autoreleasepool

    {

    [NSTimer scheduledTimerWithTimeInterval:1.0target:self selector:@selector(showTime) userInfo:nil repeats:YES];

    [[NSRunLoop currentRunLoop] run];

    }

    }

    或者直接使用GCD的计时功能替代.

    相关文章

      网友评论

          本文标题:NStimer计时器值得注意的点

          本文链接:https://www.haomeiwen.com/subject/xorlfftx.html