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


2019.3.15

注意:iOS10之前创建的NSTimer对象的方法会出现循环引用的问题,从而导致NSTimer对象无法被释放,iOS苹果为我们新增了两个新的带有block的创建NSTimer对象的方法,解决了NSTimer对象无法释放的问题。

看这篇解决NSTimer造成的循环引用的文章:https://www.jianshu.com/p/d6b5c12180cc

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

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

推荐阅读更多精彩内容