IOS 中NSTimer定时器的使用

时间:2019-04-07
本文章向大家介绍IOS 中NSTimer定时器的使用,主要包括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

// 有效释放 
- (void)viewWillDisappear:(BOOL)animated 
{ 
  [super viewWillDisappear:animated]; 
   
  [timer invalidate]; 
  timer = nil; 
} 
 
// 无效释放 
- (void)delloc 
{ 
  [timer invalidate]; 
  timer = nil; 
} 

3 计时器启用关闭继续

3.1 开始:

timer.fireDate = [NSDate distantPast]; 

3.2 停止:

timer.fireDate = [NSDate distantFuture]; 

3.3 继续:

[timer setFireDate:[NSDate date]]; 

使用示例(倒计时):

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

方法1

// 实例化方法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 
[self.timer invalidate]; 
self.timer = nil; 

方法2

// 实例化方法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]]; 



// 关闭定时器方法2 
[self.timer setFireDate:[NSDate distantFuture]]; 

方法3

// 实例化方法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]; 

// 关闭定时器方法3 
[self.timer invalidate]; 
self.timer = nil; 

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