要想計(jì)時(shí)器(Timer)不因UITableView的滑動(dòng)而停止工作油够,就得探討一下RunLoop了导绷。
RunLoop本質(zhì)和它的意思一樣是運(yùn)行著的循環(huán)赞厕,更確切的說是線程中的循環(huán)裆操。它用來接受循環(huán)中的事件和安排線程工作挫掏,并在沒有工作時(shí)瘦陈,讓線程進(jìn)入睡眠狀態(tài)鳖谈。
所以根據(jù)RunLoop的定義岁疼,當(dāng)Timer被滑動(dòng)過了,誤以為沒有工作缆娃,讓它進(jìn)入睡眠狀態(tài)了捷绒。怎樣來避免這種情況呢?我們可以先來了解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應(yīng)用程序中,默認(rèn)情況下Common Modes包含default modes,modal modes,event Tracking modes.可使用CFRunLoopAddCommonMode方法想Common Modes中添加自定義modes显押。因此扳肛,我們需要把計(jì)時(shí)器的RunLoop的Mode調(diào)整為Common模式。具體的操作如下:
1 NSTimer *timer = [NSTimer timerWithTimeInterval:1.0f target:self selector:@selector(timerAction) userInfo:nil repeats:YES];
2 //將定時(shí)器添加到runloop中
3 [[NSRunLoop currentRunLoop] addTimer:timer forMode:NSRunLoopCommonModes ];
4 [[NSRunLoop currentRunLoop] run];