定时器的使用方法
方法之一:必须调用方法来开始计时器不会自动加入执行队列
1、创建定时器
if (!_timer.valid) {
//参数依次为 间隔时间 、监听者、监听方法、参数、是否循环执行
_timer = [NSTimer scheduledTimerWithTimeInterval:间隔时间 target:监听者 selector:@selector(监听方法) userInfo:参数(nil) repeats:YES];
}
创建定时器的方法在点击按钮时候调用
2.开始计时方法
// 开始计时
_timer.fireDate = [NSDate distantPast];
3.暂停计时器的方法
// 暂停定时器
_timer.fireDate = [NSDate distantFuture];
```
###4.用lable来显示计时设计到的东西为
//定时器的监听方法(在这里面每隔设置时间段做需要循环的事情)
-(void)changeTime{
//获得lable的值
NSString *lablestr = self.time.text;
//将字符串转换为时间
NSDateFormatter *format = [[NSDateFormatter alloc]init];
format.dateFormat = @"HH:mm:ss";
NSDate *strDate = [format dateFromString:lablestr];
//当前时间上增加一秒
NSDate *newDate = [strDate dateByAddingTimeInterval:1.0];
NSString *newstr =[format stringFromDate:newDate];
self.time.text = newstr;
}
```
该方法一般写到定时器的回调方法中目的是间隔多少时间进行一次调用
而且在此之前要先设置lable的时间格式如下
-(UILabel *)time{
if (!_time) {
_time = [[UILabel alloc]init];
_time.frame = CGRectMake(20, 100, 300, 44);
_time.font = [UIFont systemFontOfSize:25];
_time.text = @"00:00:00";
_time.textAlignment = NSTextAlignmentCenter;
}
return _time;
}
5.暂停和停止计时器
-(void)clickstopbtn{
NSLog(@"暂停或停止");
// 暂停定时器
_timer.fireDate = [NSDate distantFuture];
// 将定时器从运行循环中退出
[_timer invalidate];
// 将定时器置空
_timer = nil;
}
其中必须将定时器从运行循环中退出,否则不会有暂停和停止
```
##方法之二:将定时器直接加入Runloop中让其自动执行
//开启定时器
- (void)startTimer {
//为空的时候才初始化
if (!self.timer) {
self.timer = [NSTimer timerWithTimeInterval:1 target:self selector:@selector(autoScrollImage) userInfo:nil repeats:YES];
[[NSRunLoop mainRunLoop] addTimer:self.timer forMode:NSRunLoopCommonModes];
}}
```
//停止定时器
- (void)stopTimer {
[self.timer invalidate];
self.timer = nil;
}