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;
|
如有疑问请留言或者到本站社区交流讨论,感谢阅读,希望能帮助到大家,谢谢大家对本站 的支持!
相关文章
猜你喜欢
- ASP.NET自助建站系统的域名绑定与解析教程 2025-06-10
- 个人服务器网站搭建:如何选择合适的服务器提供商? 2025-06-10
- ASP.NET自助建站系统中如何实现多语言支持? 2025-06-10
- 64M VPS建站:如何选择最适合的网站建设平台? 2025-06-10
- ASP.NET本地开发时常见的配置错误及解决方法? 2025-06-10
TA的动态
- 2025-07-10 怎样使用阿里云的安全工具进行服务器漏洞扫描和修复?
- 2025-07-10 怎样使用命令行工具优化Linux云服务器的Ping性能?
- 2025-07-10 怎样使用Xshell连接华为云服务器,实现高效远程管理?
- 2025-07-10 怎样利用云服务器D盘搭建稳定、高效的网站托管环境?
- 2025-07-10 怎样使用阿里云的安全组功能来增强服务器防火墙的安全性?
快网idc优惠网
QQ交流群
您的支持,是我们最大的动力!
热门文章
-
2025-05-25 42
-
2025-05-27 87
-
2025-06-04 73
-
2025-06-04 60
-
2025-05-29 102
热门评论

