1:NSTimer的創(chuàng)建
- (void)viewDidLoad {
[super viewDidLoad];
NSTimer *timer1 =[NSTimer timerWithTimeInterval:0.5 target:self selector:@selector(action:) userInfo:nil repeats:YES];
[timer1 fire];
}
-(void)action:(NSTimer *)timer{
NSLog(@"定時(shí)器開");
}
這時(shí)會(huì)發(fā)現(xiàn)timer的ation方法不會(huì)調(diào)用。
坑一:子線程啟動(dòng)定時(shí)器問題:
我們都知道iOS是通過runloop作為消息循環(huán)機(jī)制,主線程默認(rèn)啟動(dòng)了runloop,可是子線程沒有默認(rèn)的runloop,因此,我們在子線程啟動(dòng)定時(shí)器是不生效的。
2.NSTimer計(jì)時(shí)停止失效(比如滑動(dòng)屏幕的時(shí)候)
NSTimer *timer1 =[NSTimer timerWithTimeInterval:0.5 target:self selector:@selector(action:) userInfo:nil repeats:YES];
[[NSRunLoop currentRunLoop] addTimer:timer1 forMode:NSDefaultRunLoopMode];
}
-(void)action:(NSTimer *)timer{
NSLog(@"定時(shí)器開");
}
坑二:runloop的mode問題:
我們注意到schedule方式啟動(dòng)的timer是add到runloop的NSDefaultRunLoopMode中,這就會(huì)出現(xiàn)其他mode時(shí)timer得不到調(diào)度的問題。最常見的問題就是在UITrackingRunLoopMode,即UIScrollView滑動(dòng)過程中定時(shí)器失效。
解決方式就是把timer add到runloop的NSRunLoopCommonModes。UITrackingRunLoopMode和kCFRunLoopDefaultMode都被標(biāo)記為了common模式,所以只需要將timer的模式設(shè)置為NSRunLoopCommonModes,就可以在默認(rèn)模式和追蹤模式都能夠運(yùn)行。