当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数组中存放的模式下工作