版权声明:本文为博主原创文章,未经博主允许不得转载。 https://cloud.tencent.com/developer/article/1337650
应用场景:
1.轮播图(轮播图上的图片定时轮播)
2.跑秒按钮(点击获取验证码之后,按钮上的秒数进行倒计时)
创建定时器的方式:
1.利用NSTimer
2.利用GCD中的dispatch_source_t
代码:
利用NSTimer创建定时器的代码:
方式一:
{
self.timer = NSTimer timerWithTimeInterval:1 target:self selector:@selector(updateTimer) userInfo:nil repeats:YES;
// 添加到运行循环 NSRunLoopCommonModes:占位模式 主线程
[[NSRunLoop currentRunLoop] addTimer:self.timer forMode:NSRunLoopCommonModes]; // 如果不改变Mode模式在滑动屏幕的时候定时器就不起作用了
}
}
方式二:
}
// 在子线程中定义定时器
}
}
注意:上面两种方式创建的定时器在用户与页面进行交互的时候定时器还是有效的。方式一是将NSTimer添加到了主线程的runloop中,但添加的是NSRunLoopCommonModes模式下,如果是添加在NSDefaultRunLoopMode模式下那么当用户与页面进行交互的时候,定时器失效。方式二是开辟了一个子线程,在子线程的runloop中添加了NSTimer,此时即使模式是NSDefaultRunLoopMode,在用户与页面进行交互的时候,定时器依然有效。
利用GCD创建定时器:
}
注意:必须使用dispatch_source_cancel才能完整地执行。
demo地址:https://gitee.com/liangsenliangsen/timer
本篇文章到这里就结束了,愿大家加班不多工资多,男同胞都有女朋友,女同胞都有男朋友。