要想計時器(Timer)不因UITableView的滑動而停止工作,就得探討一下RunLoop了。
RunLoop本質和它的意思一樣是運行著的循環,更確切的說是線程中的循環。它用來接受循環中的事件和安排線程工作,并在沒有工作時,讓線程進入睡眠狀態。
所以根據RunLoop的定義,當Timer被滑動過了,誤以為沒有工作,讓它進入睡眠狀態了。怎樣來避免這種情況呢?我們可以先來了解RunLoop的幾種模式。RunLoop有Default模式、Connection模式、Modal模式、Event tracking模式和Common模式(具體模式的含義在[http://www.cnblogs.com/fmdxiangdui/p/6164350.html](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模式。具體的操作如下:
1 NSTimer *timer = [NSTimer timerWithTimeInterval:1.0f target:self selector:@selector(timerAction) userInfo:nil repeats:YES];
2 //將定時器添加到runloop中
3 [[NSRunLoop currentRunLoop] addTimer:timer forMode:NSRunLoopCommonModes ];
4 [[NSRunLoop currentRunLoop] run];