最近, 在使用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
本文探讨了在iOS开发中使用NSTimer遇到的一个问题:当界面发生变化时,NSTimer可能停止工作。文章对比了两种创建NSTimer的方法,并解释了为什么scheduledTimerWithTimeInterval会导致此问题。最后给出了一个解决方法,即通过将NSTimer添加到NSRunLoop的不同模式来确保其在各种情况下的正常运行。

1317

被折叠的 条评论
为什么被折叠?



