前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >iOS开发中创建定时器

iOS开发中创建定时器

作者头像
用户1451823
发布2018-09-13 15:23:50
8960
发布2018-09-13 15:23:50
举报
文章被收录于专栏:DannyHoo的专栏

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://cloud.tencent.com/developer/article/1337650

应用场景:

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;

代码语言:javascript
复制
// 添加到运行循环  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

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

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2018年02月26日,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
相关产品与服务
验证码
腾讯云新一代行为验证码(Captcha),基于十道安全栅栏, 为网页、App、小程序开发者打造立体、全面的人机验证。最大程度保护注册登录、活动秒杀、点赞发帖、数据保护等各大场景下业务安全的同时,提供更精细化的用户体验。
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档