由于最近面试经常有人问到关于NSTimer的一些问题,所以自己整理了一下记录了一些关键的问题
1 NSTimer为什么有会造成线程堵塞,如何解决
NSTimer是加到当前的runloop中的,就是main runloop,模式是NSDefaultRunLoopMode,而mian runloop是负责主线程事件的,如果主线程有复杂的运算,那么timer就会被堵塞导致计时不准确
解决:1 使用NSRunLoopCommonModes模式,将计时器加到其中比如
self.timer = [NSTimer timerWithTimeInterval:0.01 target:self selector:@selector(addTime) userInfo:nil repeats:YES];
[[NSRunLoop currentRunLoop] addTimer:self.timer forMode:NSRunLoopCommonModes];
2
开辟子线程,使用子线程的runloop
NSThread *thread = [[NSThread alloc] initWithTarget:self selector:@selector(newThread) object:nil];
[thread start];
- (void)newThread { @autoreleasepool {
[NSTimer scheduledTimerWithTimeInterval:2.0 target:self selector:@selector(addTime) userInfo:nil repeats:YES]; [[NSRunLoop currentRunLoop] run]; } }3 如果NSTimer一般使用一次不循环用的话,使用 dispatch_after 延时加载,等主线程界面更新再加载计时器
4 或者使用多线程GCD
2 NSTimer为什么有时不会走dealloc,如何停止NSTimer
timer对象会对object拥有一个强引用,如果object是self,那么self就被timer retain,如果timer一直不invalidated,那么dealloc就一直不会被调用
解决办法: 在viewWillDisappear的时候invalidateNSTimer对象
- (void)viewWillDisappear:(BOOL)animated{
[super viewWillDisappear:animated];
[timer invalidate];
}