IOS开发-OC学习-NSTimer的使用
上一篇博客中在改变属性值的时候使用了timer进行自动改变。关于NSTimer的更详细的用法如下:
定义一个NSTimer类型的timer,和一个count,其中timer是定时器,count是计数的,用来统计timer发生了几次。
1 NSTimer * timer; 2 NSInteger count;
计数值count初始化,timer初始化:时间间隔设定、触发函数、是否重复等:
1 count = 0; 2 timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(haha:) userInfo:nil repeats:YES];
定时器的selector函数:(设置self的两个属性,并在每次调用之后给count+1,用来计数定时器触发的次数。函数中使用kvc设置self 的属性值:
1 -(void)haha:(id)sender{ 2 NSString *nameString = [NSString stringWithFormat:@"name%d",arc4random()%100]; 3 // self.ticketName = string; 4 NSString *priceString =[NSString stringWithFormat:@"%d",arc4random()%100]; 5 [self setValue:nameString forKey:@"ticketName"]; 6 [self setValue:priceString forKey:@"ticketPrice"]; 7 count++; 8 }
在监测到self的属性值变化时做出如下响应 1 //kvo,在观察的值变化的时候进行执行响应的函数 2 -(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context{
3 // 如果定时次数小于10,执行打印 4 if (count!=10) { 5 if ([keyPath isEqualToString:@"ticketName"]) { 6 //通过change打印 7 NSLog(@"ticketName的值被改变成了%@",[change objectForKey:@"new"]); 8 // NSLog(@"ticketName的值被改变成了%@",self.ticketName);//通过点语法打印 9 }else{ 10 11 NSLog(@"ticketPrice的值被改变成了%@",[change objectForKey:@"new"]);//通过change打印 12 // NSLog(@"ticketPrice的值被改变成了%@",self.ticketPrice);//通过点语法打印 13 } 14 }else{//如果定时器定时次数大于10,使定时器失效 15 [timer invalidate]; 16 if([timer isValid]{
17 // NSLog(@"定时器失效");
} 18 NSLog(@"%d",[timer isValid]); 19 20 } 21 22 }
如果count小于10,那么执行打印self属性值的分支,如果count等于10,那么使用[timer invalidate];函数来失能timer定时器,并且使用[timer isValid];去判断timer是否已经失能,如果失能,打印出定时器实效,并在最后打印出[timer isValid]的值。