NSTimer注意事项

使用的时候一定要加到RunLoop里的NSEventTrackingRunLoopMode模式

不然NSTimer可能会暂停计时

特别是页面有UITableView或者UIScrollView

因为NSTimer创建的时候会默认加入到RunLoopNSDefaultRunLoopMode模式里

但是当界面出现滑动的时候

RunLoop模式会发生改变

变成NSEventTrackingRunLoopMode模式

所以当页面滑动的时候就不会去执行

解决办法就是创建完成之后

手动加入RunLoopNSEventTrackingRunLoopMode模式里

这样界面出现滑动的时候就没问题了

1
2
3
NSTimer *timer=[NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(add) userInfo:nil repeats:YES];

[[NSRunLoop mainRunLoop] addTimer:timer forMode:NSRunLoopCommonModes];

为什么是NSRunLoopCommonModes

因为NSRunLoopCommonModes包含很多模式

还有就是NSTimer会对self强引用

一定要及时置空

1
2
[timer invalidate];
timer = nil;