iOS 几种定定时器实现

本文介绍了使用CGD及NSTimer两种方式实现倒计时功能的具体代码示例。CGD部分通过dispatch_source创建定时器,并利用dispatch_queue进行调度;而NSTimer则直接采用schedule方法启动定时任务。两种方案均实现了按钮禁用与倒计时显示等功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


1.CGD定时器

- (IBAction)countDown:(id)sender {
    __block int currentSeconds = 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_TIME_NOW, 1.0 * NSEC_PER_SEC, 0 * NSEC_PER_SEC);
    dispatch_source_set_event_handler(timer, ^{
        if (currentSeconds <= 0) {
            dispatch_source_cancel(timer);
            dispatch_async(dispatch_get_main_queue(), ^{
                self.timeButton.enabled = YES;
                [self.timeButton setTitle:@"验证" forState:UIControlStateNormal];
            });
        } else {
            currentSeconds--;
            dispatch_async(dispatch_get_main_queue(), ^{
                self.timeButton.enabled = NO;
                [self.timeButton setTitle:[NSString stringWithFormat:@"%d秒",currentSeconds] forState:UIControlStateNormal];
            });
        }
    });
    //启动定时器
    dispatch_resume(timer);
}

 

 

 

2.NSTimer定时器
-(void)lookBackClick:(UIButton *)btn
{
    
    NSDictionary *params = @{@"phone":fieldMobile.text};
    [NetworkHandle post:CAPTCHA_URL parameters:params success:^(AFHTTPRequestOperation *operation, NSDictionary *response) {
        NSLog(@"------%@",operation.responseString);
        NSDictionary *rs = [NSJSONSerialization JSONObjectWithData:operation.responseData options:NSJSONReadingMutableContainers error:nil];
        
        if (rs) {
            codeString = rs[@"ds"];
            seconds = 60;
            [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(onTimer:) userInfo:nil repeats:YES];
            [getButton setEnabled:NO];

        }
    }];
}
- (void)onTimer:(id)userInfo {
    [getButton setTitle:[NSString stringWithFormat:@"%d", --seconds] forState:UIControlStateDisabled];
    
    if (seconds == 0) {
        [getButton setTitle:@"获取验证码" forState:UIControlStateNormal];
        [getButton setEnabled:YES];

        NSTimer *timer = (NSTimer *)userInfo;
        [timer invalidate];
    }
}

 

 


 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值