最近, 在使用NSTimer
的时候,发现了一个问题,在当前界面NSTimer
的方法是可以执行的,但是当我push到下一界面, 做完相关操作,pop回来的时候,UI刷新,再次调用定时器时,发现方法竟然不执行了, 开始以为是线程阻塞,后来发现是NSTimer
创建的问题。
NSTimer
创建是有两种方式的:
+ (NSTimer *)timerWithTimeInterval:(NSTimeInterval)ti target:(id)aTarget selector:(SEL)aSelector userInfo:(nullable id)userInfo repeats:(BOOL)yesOrNo;
+ (NSTimer *)scheduledTimerWithTimeInterval:(NSTimeInterval)ti target:(id)aTarget selector:(SEL)aSelector userInfo:(nullable id)userInfo repeats:(BOOL)yesOrNo;
这两种方式在RunLoop
里面是不一样的。
我是这样写的
[NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:@selector(scheduledTime) userInfo:nil repeats:YES];
scheduledTimerWithTimeInterval:
这个方法会默认把NSTimer
以NSDefaultRunLoopMode
添加到主Runloop
上,而当UI刷新的时候,就不是NSDefaultRunLoopMode
了,这样,NSTimer
就会停了。
NSDefaultRunLoopMode:
NSTimer
只有在默认模式下(NSDefaultRunLoopMode)
工作,切换到其他模式不再工作,比如拖拽了界面上的某个控件(会切换成UITrackingRunLoopMode
)
可以改成这样:
NSTimer *timer = [NSTimer timerWithTimeInterval:0.1 target:self selector:@selector(scheduledTime) userInfo:nil repeats:YES];
[[NSRunLoop mainRunLoop] addTimer:timer forMode:NSRunLoopCommonModes];
关于RunLoop的应用
http://www.cocoachina.com/ios/20161212/18335.html
具体可以看一下 RunLoop 的机制
http://www.jianshu.com/p/4bc01f5269e7