IOS 中NSTimer定时器的使用

2025-05-29 0 44

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;

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

收藏 (0) 打赏

感谢您的支持,我会继续努力的!

打开微信/支付宝扫一扫,即可进行扫码打赏哦,分享从这里开始,精彩与您同在
点赞 (0)

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。

快网idc优惠网 建站教程 IOS 中NSTimer定时器的使用 https://www.kuaiidc.com/90303.html

相关文章

发表评论
暂无评论