解决UITableView上计时器(Timer)的滑动问题

时间:2023-03-10 04:45:08
解决UITableView上计时器(Timer)的滑动问题

要想计时器(Timer)不因UITableView的滑动而停止工作,就得探讨一下RunLoop了。

RunLoop本质和它的意思一样是运行着的循环,更确切的说是线程中的循环。它用来接受循环中的事件和安排线程工作,并在没有工作时,让线程进入睡眠状态。

所以根据RunLoop的定义,当Timer被滑动过了,误以为没有工作,让它进入睡眠状态了。怎样来避免这种情况呢?我们可以先来了解RunLoop的几种模式。RunLoop有Default模式、Connection模式、Modal模式、Event tracking模式和Common模式(具体模式的含义在http://www.cnblogs.com/fmdxiangdui/p/6164350.html介绍)。在Cocoa应用程序中,默认情况下Common Modes包含default modes,modal modes,event Tracking modes.可使用CFRunLoopAddCommonMode方法想Common Modes中添加自定义modes。因此,我们需要把计时器的RunLoop的Mode调整为Common模式。具体的操作如下:

 NSTimer *timer = [NSTimer timerWithTimeInterval:1.0f target:self selector:@selector(timerAction) userInfo:nil repeats:YES];
//将定时器添加到runloop中
[[NSRunLoop currentRunLoop] addTimer:timer forMode:NSRunLoopCommonModes ];
[[NSRunLoop currentRunLoop] run];