NSTimer 是iOS开发中常用的定时器, NSTimer的使用常见的有两种方式:
1. [NSTimer timerWithTimeInterval:2.0 target:self selector:@selector(run) userInfo:nil repeats:YES];
- (void)addTimer {
NSTimer *timer = [NSTimer timerWithTimeInterval:1.0
target:self
selector:@selector(timerAction)
userInfo:nil repeats:YES];
// 方式1. NSDefaultRunLoopMode模式,切换RunLoop模式,定时器停止工作.
[[NSRunLoop currentRunLoop] addTimer:timer forMode:NSDefaultRunLoopMode];
// 方式2. UITrackingRunLoopMode模式,切换RunLoop模式,定时器停止工作.
[[NSRunLoop currentRunLoop] addTimer:timer forMode:UITrackingRunLoopMode];
// 方式3. common modes的模式,以下三种模式的组合模式
// NSDefaultRunLoopMode & NSModalPanelRunLoopMode & NSEventTrackingRunLoopMode
[[NSRunLoop currentRunLoop] addTimer:timer forMode:NSRunLoopCommonModes];
}
补充:
NSRunLoop的几种模式:(基于Cocoa框架下)
1.开发中常用的就是默认模式和组合模式,其中默认模式下,当页面出现scrollView滑动式,会切入NSEventTrackingRunLoopMode模式下工作,造成定时器中断
//1.默认模式:该模式中几乎包含了所有输入源(NSConnection除外),一般情况下应使用此模式。
NSDefaultRunLoopMode:
//2.Connection模式:处理NSConnection对象相关事件,系统内部使用
NSConnectionReplyMode:
//3.Panel模式:该模式用于过滤在模态面板中处理的事件(Mac App)。
NSModalPanelRunLoopMode:
//4.跟踪模式:一般用于UIScrollView的页面滑动时
NSEventTrackingRunLoopMode:
//5.组合模式: 默认包含NSDefaultRunLoopMode、NSModalPanelRunLoopMode、NSEventTrackingRunLoopMode这三个模式。
NSRunLoopCommonModes:
2.[NSTimer scheduledTimerWithTimeInterval:2.0 target:self selector:@selector(run) userInfo:nil repeats:YES]
- (void) addTimer2 {
// scheduledTimer创建的定时器,默认添加到当前当前RunLoop的NSDefaultRunLoopMode模式下
NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:1.0
target:self
selector:@selector(timerAction)
userInfo:nil repeats:YES];
// 修改模式
[[NSRunLoop currentRunLoop] addTimer:timer forMode:NSRunLoopCommonModes];
}
3.子线程中使用[NSTimer scheduledTimerWithTimeInterval:2.0 target:self selector:@selector(run) userInfo:nil repeats:YES]
- (void)timer3{
__block NSTimer *timer ;
dispatch_async(dispatch_get_global_queue(0, 0), ^{
timer = [NSTimer scheduledTimerWithTimeInterval:1.0
target:self
selector:@selector(timerAction)
userInfo:nil repeats:YES];
[[NSRunLoop currentRunLoop] run];
});
}
网友评论