美文网首页
iOS---NStimer的计时问题

iOS---NStimer的计时问题

作者: 彬至睢阳 | 来源:发表于2017-12-09 11:31 被阅读0次

    NStimer不是一个精准的,理由:

    1、NSTimer加在main runloop中,模式是NSDefaultRunLoopMode,main负责所有主线程事件,例如UI界面的操作,复杂的运算,这样在同一个runloop中timer就会产生阻塞。

    2、模式的改变。主线程的 RunLoop 里有两个预置的 Mode:kCFRunLoopDefaultMode 和 UITrackingRunLoopMode。

    当你创建一个 Timer 并加到 DefaultMode 时,Timer 会得到重复回调,但此时滑动一个ScrollView时,RunLoop 会将 mode 切换为 TrackingRunLoopMode,这时 Timer 就不会被回调,并且也不会影响到滑动操作。所以就会影响到NSTimer不准的情况。

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

    怎样实现一个精确的NSTimer?

    方法一:

    1、在主线程中进行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)timerMethod2 {

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

    [thread start];

    }

    - (void)newThread

    {

    @autoreleasepool

    {

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

    [[NSRunLoop currentRunLoop] run];

    }

    }

    结论:一开始的时候系统就为我们将主线程的main runloop隐式的启动了。在创建线程的时候,可以主动获取当前线程的runloop。每个子线程对应一个runloop

    方法二:

    使用GCD代替

    相关文章

      网友评论

          本文标题:iOS---NStimer的计时问题

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