亡羊補(bǔ)牢匪傍,為時(shí)不晚
面試被問(wèn)到,一直沒(méi)有注意過(guò)观挎,在此補(bǔ)上琴儿。
問(wèn)題描述
控制器中存在定時(shí)器以及tableview,當(dāng)滑動(dòng)tableview時(shí)嘁捷,定時(shí)器停止計(jì)時(shí)造成,tableview再次停止后,計(jì)時(shí)恢復(fù)普气。
代碼測(cè)試
使用label顯示計(jì)時(shí)情況
計(jì)時(shí)
方案一:將定時(shí)器添加到其他線程谜疤,并開(kāi)啟runloop
dispatch_async(dispatch_get_global_queue(0, 0), ^{
self.timer = [NSTimer scheduledTimerWithTimeInterval:0.2 target:self selector:@selector(timeNumChange) userInfo:nil repeats:YES];
[[NSRunLoop currentRunLoop] run];
});
- (void)timeNumChange {
self.count++;
dispatch_async(dispatch_get_main_queue(), ^{
self.timeNum.text = [NSString stringWithFormat:@"runloop:%ld",self.count];
});
}
方案二:將timer添加到指定mode(UITrackingRunLoopMode、NSRunLoopCommonModes)
self.timer = [NSTimer scheduledTimerWithTimeInterval:0.2 target:self selector:@selector(timeNumChange) userInfo:nil repeats:YES];
[[NSRunLoop currentRunLoop] addTimer:self.timer forMode:UITrackingRunLoopMode];
- (void)timeNumChange {
self.count++;
self.timeNum.text = [NSString stringWithFormat:@"runloop:%ld",self.count];
}
最后轉(zhuǎn)載一篇更詳細(xì)的文章:深入理解RunLoop