定时器在开发中经常使用的,下面说两种定时器的的实现。
1:使用 GCD实现 (防止按钮重复点击)
//计时器
-(void)startTime:(UIButton *)sender{
__block int timeout = 60;
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_source_t timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
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.userInteractionEnabled = YES;
[sender setTitle:@"开启倒计时" forState:UIControlStateNormal];
});
}else{
NSString *strTime = [NSString stringWithFormat:@"剩余时间:%.2d", timeout];
dispatch_async(dispatch_get_main_queue(), ^{
sender.userInteractionEnabled = NO;
[sender setTitle:strTime forState:UIControlStateNormal];
});
timeout--;
}
});
dispatch_resume(timer);
}
2:使用 RAC 实现 (防止按钮重复点击)
- (IBAction)start:(UIButton *)sender {
sender.userInteractionEnabled = NO;
[self Timer:sender];
}
-(void)Timer:(UIButton *)sender{
static NSInteger seconds;
seconds = 10;
//take :只去前11个信号,可按要求自己改其他的参数
[[[RACSignal interval:1 onScheduler:[RACScheduler mainThreadScheduler]] take:11]
subscribeNext:^(NSDate * date) {
_timeLabel.text = [NSString stringWithFormat:@"%ld",seconds];
seconds--;
if (seconds < 0) {
sender.userInteractionEnabled = YES;
return ;
}
}];
}