美文网首页
不被干扰的NSTimer

不被干扰的NSTimer

作者: 倪大头 | 来源:发表于2018-05-08 15:21 被阅读17次

    当timer被添加在cell上时,滑动cell会造成timer失效,因为cell的滑动(UITrackingRunLoopMode)屏蔽了NSDefaultRunLoopMode。

    可以把timer移到其他mode中,用scheduledTimerWithTimeInterval创建时会默认使用NSDefaultRunLoopMode,下面用NSTimer的类方法timerWithTimeInterval创建,并且手动指定mode:

    NSTimer *timer = [NSTimer timerWithTimeInterval:1 repeats:YES block:^(NSTimer * _Nonnull timer) {
        cellLabel.text = [NSString stringWithFormat:@"%ld",cellLabel.text.integerValue + 1];
    }];
    [[NSRunLoop currentRunLoop] addTimer:timer forMode:NSRunLoopCommonModes];
    [timer fire];
    

    这样在滑动cell的时候timer是正常运转的

    NSDefaultRunLoopMode、UITrackingRunLoopMode才是真正存在的模式,
    NSRunLoopCommonModes并不是一个真的模式,它只是一个标记,timer能在_commonModes数组中存放的模式下工作

    相关文章

      网友评论

          本文标题:不被干扰的NSTimer

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