- 父类是NSObject
- 名称:“定时器”
- 作用:
- 在指定的时间执行指定的任务
- 每隔一段时间执行指定的任务
使用方法
- 开启一个定时任务
//每隔ti秒,调用一次aTarget的aSelector方法,yesOrNo决定了是否重复执行这个任务.
//会返回一个NSTimer类型的指针,让其成为控制器的成员变量,方便日后关闭定时器,因为定时器的关闭方法是对象方法
+(NSTimer *)scheduledTimerWithTimeInterval:(NSTimeInterval)ti target:(id)aTarget
selector:(SEL)aSelector
userInfo:(id)userInfo
repeats:(BOOL)yesOrNo;
```
- 停止定时器
```objc
//一旦定时器被停止了,就不能再次执行任务。只能再创建一个新的定时器才能执行新的任务
-(void)invalidate;
解决定时器在主线程不工作的问题
//创建新的NSTimer,并每隔2秒后执行'next'方法,返回指针
NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:2 target:self selector:@selector(next) userInfo:nil repeats:YES];
//让主线程抽空关注Timer的执行
[[NSRunLoop mainRunLoop] addTimer:timer forMode:NSRunLoopCommonModes];
NSTimer与Runloop
/*
说明:
(1)runloop一启动就会选中一种模式,当选中了一种模式之后其它的模式就动不了。一个mode里面可以添加多个NSTimer,也就是说以后当创建NSTimer的时候,可以指定它是在什么模式下运行的。
(2)它是基于时间的触发器,说直白点那就是时间到了我就触发一个事件,触发一个操作。基本上说的就是NSTimer;往runloop中添加一个定时器事件,该定时器事件运行在默认运行模式下面
(3)相关代码
*/
- (void)timer2
{
//NSTimer 调用了scheduledTimer方法,那么会自动添加到当前的runloop里面去,而且runloop的运行模式kCFRunLoopDefaultMode
NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:2.0 target:self selector:@selector(run) userInfo:nil repeats:YES];
//更改模式
[[NSRunLoop currentRunLoop] addTimer:timer forMode:NSRunLoopCommonModes];
}
- (void)timer1
{
// [NSTimer scheduledTimerWithTimeInterval:2.0 target:self selector:@selector(run) userInfo:nil repeats:YES];
NSTimer *timer = [NSTimer timerWithTimeInterval:2.0 target:self selector:@selector(run) userInfo:nil repeats:YES];
//定时器添加到UITrackingRunLoopMode模式,一旦runloop切换模式,那么定时器就不工作
// [[NSRunLoop currentRunLoop] addTimer:timer forMode:UITrackingRunLoopMode];
//定时器添加到NSDefaultRunLoopMode模式,一旦runloop切换模式,那么定时器就不工作
// [[NSRunLoop currentRunLoop] addTimer:timer forMode:NSDefaultRunLoopMode];
//占位模式:common modes标记
//被标记为common modes的模式 kCFRunLoopDefaultMode UITrackingRunLoopMode
[[NSRunLoop currentRunLoop] addTimer:timer forMode:NSRunLoopCommonModes];
// NSLog(@"%@",[NSRunLoop currentRunLoop]);
//Mode表示runloop的运行模式
//设置添加到runloop的NSDefaultRunLoopMode运行模式下
/*
//NSDefaultRunLoopMode 表示只有当runloop的运行模式处于默认模式的情况写才工作,其他模式不工作
// [[NSRunLoop currentRunLoop]addTimer:timer forMode:NSDefaultRunLoopMode];
*/
//设置添加到runloop的UITrackingRunLoopMode运行模式下
/*
//UITrackingRunLoopMode 表示只有当runloop的运行模式处于界面跟踪的情况才工作,其他模式不工作
// [[NSRunLoop currentRunLoop]addTimer:timer forMode:UITrackingRunLoopMode];
*/
//设置添加到所有被标记为NSRunLoopCommonModes的运行模式下
/*
NSRunLoopCommonModes占位模式:意味着吧timer添加到所有被标记为NSRunLoopCommonModes的运行模式下面
被标记为NSRunLoopCommonModes的所有运行模式:
UITrackingRunLoopMode|kCFRunLoopDefaultMode
0 : <CFString 0x10aa0ca40 [0x109b817b0]>{contents = "UITrackingRunLoopMode"}
2 : <CFString 0x109ba1b40 [0x109b817b0]>{contents = "kCFRunLoopDefaultMode"}
}
- (void)run
{
NSLog(@"---run---%@",[NSRunLoop currentRunLoop].currentMode);
}
- (IBAction)btnClick {
NSLog(@"---btnClick---");
}