我是靠谱客的博主 霸气奇异果,这篇文章主要介绍IOS 中NSTimer定时器的使用,现在分享给大家,希望可以做个参考。

IOS 中NSTimer定时器的使用

NSTimery 定时器,主要用于进行定时执行指定方法,常用场景如:获取验证码的按钮倒计时;图片轮播定时。

1 使用注意事项:

1.1 倒计时时间间隔(时间单位是秒)
1.2 指定的执行方法
1.3 实现指定执行方法的对象
1.4 是否重复执行
2 对象的内存管理及销毁
2.1 使用方法" invalidate "进行停止
2.2 将对象设置为" nil "
2.3 特别是在返回到其他视图控制器的时候,要在方法" - (void)viewWillDisappear:
     (BOOL)animated "中(注意:不能在方法" - (void)dealloc 在设置)将timer停止,并设置为nil

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
// 有效释放 - (void)viewWillDisappear:(BOOL)animated { [super viewWillDisappear:animated]; [timer invalidate]; timer = nil; } // 无效释放 - (void)delloc { [timer invalidate]; timer = nil; }

3 计时器启用关闭继续

3.1 开始:

复制代码
1
timer.fireDate = [NSDate distantPast];

3.2 停止:

复制代码
1
timer.fireDate = [NSDate distantFuture];

3.3 继续:

复制代码
1
[timer setFireDate:[NSDate date]];

使用示例(倒计时):

三种实例化方法,级对应的停止方法

方法1

复制代码
1
2
3
4
5
6
7
8
9
10
// 实例化方法1 初始化后即开始执行 if (self.timer == nil) { self.time = 10.0; // 带参数 NSNumber *number = @(self.time); self.timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(countDownTime:) userInfo:number repeats:YES]; // 非必要设置,实际已设置为 NSDefaultRunLoopMode 模式 [[NSRunLoop currentRunLoop] addTimer:self.timer forMode:NSRunLoopCommonModes]; }
复制代码
1
2
3
// 关闭定时器方法1 [self.timer invalidate]; self.timer = nil;

方法2

复制代码
1
2
3
4
5
6
7
8
9
10
// 实例化方法2 初始后化,需要调用" setFireDate "才开始执行 if (self.timer == nil) { self.timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(countDownTime:) userInfo:nil repeats:YES]; // 非必要设置,实际已设置为 NSDefaultRunLoopMode 模式 [[NSRunLoop currentRunLoop] addTimer:self.timer forMode:NSRunLoopCommonModes]; [self.timer setFireDate:[NSDate distantFuture]]; } self.time = 10.0; [self.timer setFireDate:[NSDate distantPast]];
复制代码
1
2
// 关闭定时器方法2 [self.timer setFireDate:[NSDate distantFuture]];

方法3

复制代码
1
2
3
4
5
6
7
8
9
// 实例化方法3 初始化后,需要调用" fire "才开始执行 if (self.timer == nil) { self.timer = [NSTimer timerWithTimeInterval:1.0 target: self selector:@selector(countDownTime:) userInfo:nil repeats:YES]; // 必须设置 NSRunLoop 线程池,否则无效 [[NSRunLoop currentRunLoop] addTimer:self.timer forMode:NSRunLoopCommonModes]; } self.time = 10.0; [self.timer fire];
复制代码
1
2
3
// 关闭定时器方法3 [self.timer invalidate]; self.timer = nil;

如有疑问请留言或者到本站社区交流讨论,感谢阅读,希望能帮助到大家,谢谢大家对本站 的支持!

最后

以上就是霸气奇异果最近收集整理的关于IOS 中NSTimer定时器的使用的全部内容,更多相关IOS内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(120)

评论列表共有 0 条评论

立即
投稿
返回
顶部