//NSTimer導致誤差的原因:
/*
1、NSTimer加在main runloop中,模式是NSDefaultRunLoopMode,main負責所有主線程事件,例如UI界面的操作,複雜的運算,這樣在同一個runloop中timer就會產生阻塞。
2、模式的改變。主線程的 RunLoop 裏有兩個預置的 Mode:kCFRunLoopDefaultMode 和 UITrackingRunLoopMode。
當你創建一個 Timer 並加到 DefaultMode 時,Timer 會得到重複回調,但此時滑動一個ScrollView時,RunLoop 會將 mode 切換爲 TrackingRunLoopMode,這時 Timer 就不會被回調,並且也不會影響到滑動操作。所以就會影響到NSTimer不準的情況。
PS:DefaultMode 是 App 平時所處的狀態,rackingRunLoopMode 是追蹤 ScrollView 滑動時的狀態。
*/
//解決的方法:
//1、在主線程中進行NSTimer操作,但是將NSTimer實例加到main runloop的特定mode(模式)中。避免被複雜運算操作或者UI界面刷新所幹擾。
self.timer = [NSTimer timerWithTimeInterval:1 target:self selector:@selector(showTime) userInfo:nil repeats:YES];
[[NSRunLoop currentRunLoop] addTimer:self.timer forMode:NSRunLoopCommonModes];
}
- (void)timerMethod2 {
//2、在子線程中進行NSTimer的操作,再在主線程中修改UI界面顯示操作結果;
NSThread *thread = [[NSThread alloc] initWithTarget:self selector:@selector(newThread) object:nil];
[thread start];
}
-(void)newThread
{
@autoreleasepool {
[NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(showTime) userInfo:nil repeats:YES];
[[NSRunLoop currentRunLoop] run];
}
}
-(void)showTime
{
//1.一開始的時候系統就爲我們將主線程的main runloop隱式的啓動了。
//2.在創建線程的時候,可以主動獲取當前線程的runloop。每個子線程對應一個runloop
}
NSTimer導致誤差的原因
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.