iOS开发中创建定时器

应用场景:

1.轮播图(轮播图上的图片定时轮播)

2.跑秒按钮(点击获取验证码之后,按钮上的秒数进行倒计时)
创建定时器的方式:

1.利用NSTimer

2.利用GCD中的dispatch_source_t
代码:

利用NSTimer创建定时器的代码:

方式一:

  • (void)startTimer

{

self.timer = [NSTimer timerWithTimeInterval:1 target:self selector:@selector(updateTimer) userInfo:nil repeats:YES];

// 添加到运行循环  NSRunLoopCommonModes:占位模式  主线程

[[NSRunLoop currentRunLoop] addTimer:self.timer forMode:NSRunLoopCommonModes];  // 如果不改变Mode模式在滑动屏幕的时候定时器就不起作用了

}

  • (void)updateTimer{

    NSLog(@”%lu”, time);

    time ++;

    if (time > 10) {

    [self.timer invalidate];
    

    }

}
方式二:

  • (void)starTimerInChildThread{

    [NSThread detachNewThreadSelector:@selector(bannerStart) toTarget:self withObject:nil];

}

// 在子线程中定义定时器

  • (void)bannerStart{

    NSLog(@”。。。”);

    self.timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(updateTimer) userInfo:nil repeats:YES];

    [[NSRunLoop currentRunLoop] addTimer:self.timer forMode:NSDefaultRunLoopMode];

    [[NSRunLoop currentRunLoop] run];

}

  • (void)updateTimer{

    NSLog(@”%lu”, time);

    time ++;

    if (time > 10) {

    [self.timer invalidate];
    

    }

}
注意:上面两种方式创建的定时器在用户与页面进行交互的时候定时器还是有效的。方式一是将NSTimer添加到了主线程的runloop中,但添加的是NSRunLoopCommonModes模式下,如果是添加在NSDefaultRunLoopMode模式下那么当用户与页面进行交互的时候,定时器失效。方式二是开辟了一个子线程,在子线程的runloop中添加了NSTimer,此时即使模式是NSDefaultRunLoopMode,在用户与页面进行交互的时候,定时器依然有效。

利用GCD创建定时器:

  • (void)go{

    __block NSInteger time = 0;

    // 倒计时时间

    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 (time > 10) {

        dispatch_source_cancel(_timer);
    
       dispatch_async(dispatch_get_main_queue(), ^{
    
            NSLog(@"计时结束..");
    
       });
    
    }else{
    
        dispatch_async(dispatch_get_main_queue(), ^{
    
            NSLog(@"---%lu", time);
    
        });
    
       time ++;
    
    }
    

    });

    dispatch_resume(_timer);

}
注意:必须使用dispatch_source_cancel才能完整地执行。

demo地址:https://gitee.com/liangsenliangsen/timer

本篇文章到这里就结束了,愿大家加班不多工资多,男同胞都有女朋友,女同胞都有男朋友。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值