iOS实现倒计时的三种方式

iOS实现倒计时的三种方式

做iOS app开发的过程当中,经常会出现获取验证码等需求,这个时候一般会使用倒计时来提示用户,本文主要总结iOS开发中常用的三种倒计时的实现方式。

Thread方式实现

NSTimer方式实现 (此种方式实现的时候,要注意Timer invalidate的时机,防止循环引用)

GCD方式实现

直接上代码吧

#define TIMECOUNT 60

@interface ViewController ()
@property (strong, nonatomic) IBOutlet UIButton *firstBtn;
@property (strong, nonatomic) IBOutlet UIButton *secondBtn;
@property (strong, nonatomic) IBOutlet UIButton *thirdBtn;

@property (assign, nonatomic) int count;
@property (nonatomic, strong) NSTimer *timer;
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    self.count = TIMECOUNT;
}

- (void)viewDidDisappear:(BOOL)animated {
    //页面消失的时候暂停定时器,防止出现循环引用,导致内存泄漏
    [self.timer invalidate];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

//------------***第一种方法***------------
#pragma mark 线程Thread方式实现
- (IBAction)firstBtnAction:(id)sender {
    //创建一个后台线程执行计时操作
    [self performSelectorInBackground:@selector(timerThread) withObject:nil];
}

- (void)timerThread {
    for (int i = TIMECOUNT; i >= 0 ; i--) {
        self.count--;
        //切换到主线程中更新UI
        [self performSelectorOnMainThread:@selector(updateFirstBtn) withObject:nil waitUntilDone:YES];
        sleep(1);
    }
}

//更新UI
- (void)updateFirstBtn {
    NSString *str = nil;
    if (self.count == 0) {
        str = [NSString stringWithFormat:@"点击获取验证码"];
        self.firstBtn.userInteractionEnabled = YES;
    } else {
        str = [NSString stringWithFormat:@"%d秒后重新获取",self.count];
        self.firstBtn.userInteractionEnabled = NO;
    }
    [self.firstBtn setTitle:str forState:UIControlStateNormal];
}

//------------***第二种方法***------------
#pragma mark NSTimer实现
- (IBAction)secondBtnAction:(id)sender {
    self.timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(handleTimer) userInfo:nil repeats:YES];
}
//定时操作,更新UI
- (void)handleTimer {
    if (self.count == 0) {
        self.secondBtn.userInteractionEnabled = YES;
        [self.secondBtn setTitle:[NSString stringWithFormat:@"点击获取验证码"] forState:UIControlStateNormal];
        self.count = TIMECOUNT;
        [self.timer invalidate];
    } else {
        self.secondBtn.userInteractionEnabled = NO;
        [self.secondBtn setTitle:[NSString stringWithFormat:@"%d秒后重新获取",self.count] forState:UIControlStateNormal];
    }
    self.count--;
}

//------------***第三种方法***------------
/**
 *  1、获取或者创建一个队列,一般情况下获取一个全局的队列
 *  2、创建一个定时器模式的事件源
 *  3、设置定时器的响应间隔
 *  4、设置定时器事件源的响应回调,当定时事件发生时,执行此回调
 *  5、启动定时器事件
 *  6、取消定时器dispatch源,【必须】
 *
 */
#pragma mark GCD实现
- (IBAction)thirdBtnAction:(id)sender {
    __block NSInteger second = TIMECOUNT;
    //(1)
    dispatch_queue_t quene = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    //(2)
    dispatch_source_t timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, quene);
    //(3)
    dispatch_source_set_timer(timer, DISPATCH_TIME_NOW, 1 * NSEC_PER_SEC, 0 * NSEC_PER_SEC);
    //(4)
    dispatch_source_set_event_handler(timer, ^{
        dispatch_async(dispatch_get_main_queue(), ^{
            if (second == 0) {
                self.thirdBtn.userInteractionEnabled = YES;
                [self.thirdBtn setTitle:[NSString stringWithFormat:@"点击获取验证码"] forState:UIControlStateNormal];
                second = TIMECOUNT;
                //(6)
                dispatch_cancel(timer);
            } else {
                self.thirdBtn.userInteractionEnabled = NO;
                [self.thirdBtn setTitle:[NSString stringWithFormat:@"%ld秒后重新获取",second] forState:UIControlStateNormal];
                second--;
            }
        });
    });
    //(5)
    dispatch_resume(timer);
}

@end

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • iOS中计时器常用的有两种方式 使用NSTimer类(Swift 中更名为 Timer) NSTimer 常用的初...
    superDg阅读 1,891评论 0 1
  • 倒计时实现由三种方式,一种是NSTimer,第二种是是CADisplayLink,第三种是通过GCD的方式来实现,...
    FlyElephant阅读 3,593评论 0 7
  • 发现 关注 消息 iOS 第三方库、插件、知名博客总结 作者大灰狼的小绵羊哥哥关注 2017.06.26 09:4...
    肇东周阅读 12,283评论 4 61
  • 前几天,赶巧的家里频频有人需要医疗资源,无耐,倾尽我以往的资源四处托人打线,其中就不乏都以前工作的同事,想想也是许...
    Youlanyoyo阅读 297评论 0 0
  • 很多钓友都应该听说过“冬腥、夏臭、秋清香”的钓鱼谚语。在实际应用中,“秋清香”的含义应该更广泛一些。虽然夏季的雨水...
    钓侠阅读 749评论 0 0