ios 两种实现定时器的不同方
一、 NSTimer
(还可以传值,做你想做的事)
- (IBAction)timerAction:(UIButton *)sender {
_timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(countDown:) userInfo:@{@"btn" : sender} repeats:YES];
}
当你所需要定时的时间走完之后重新定时列如60秒
- (void)countDown:(NSTimer *)timer{
UIButton *btn = timer.userInfo[@"btn"];
[btn setUserInteractionEnabled:NO];
count -- ;
[btn setTitle:[NSString stringWithFormat:@"%lds",(long)count] forState:UIControlStateNormal];
if (count == 0) {
count = 60;
[btn setTitle:@"重新发送" forState:UIControlStateNormal];
[btn setUserInteractionEnabled:YES];
[_timer invalidate];
_timer = nil;
}
}
别忘了释放_time,但是网上好多说法--这样释放不掉timer,因为被RunLoop强引用了...
-(void)dealloc
{
[_timer invalidate];
_timer = nil;
NSLog(@"%@ dealloc", NSStringFromClass([self class]));
}
二、使用CGD
#pragma mark GCD 倒计时
- (IBAction)gcdAction:(UIButton *)sender {
[sender setUserInteractionEnabled:NO];
__block int timeout = 60;
dispatch_queue_t quene = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_source_t timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, quene);
dispatch_source_set_timer(timer, dispatch_walltime(NULL, 0), 1.0 * NSEC_PER_SEC, 0);
dispatch_source_set_event_handler(timer, ^{
if (timeout == 0) {
dispatch_source_cancel(timer);
dispatch_async(dispatch_get_main_queue(), ^{
[sender setUserInteractionEnabled:YES];
[sender setTitle:@"重新发送" forState:UIControlStateNormal];
});
}else{
timeout -- ;
dispatch_async(dispatch_get_main_queue(), ^{
[sender setTitle:[NSString stringWithFormat:@"%ds",timeout] forState:UIControlStateNormal];
});
}
});
dispatch_resume(timer);
}
闲下来时就因该学习一下.Demo以上传到gitHub上面 感兴趣的小伙伴可以下载探讨一下,有问题或者建议欢迎骚扰!
笔尖下的诱惑~