NSTimer的使用(精简)
来源:互联网 发布:做淘宝售后几天上手 编辑:程序博客网 时间:2024/06/05 22:59
简述:NSTimer是iOS系统的计时控件,下面介绍NSTimer的使用,简单详细:
- Timer的开启:
+ (NSTimer *)scheduledTimerWithTimeInterval:(NSTimeInterval)interval repeats:(BOOL)repeats block:(void (^)(NSTimer *timer))block
创建一个timer对象,并且默认将timer添加Runloop系统中,timer开始计时;该方法使用与iOS 10以后,iOS 10以前使用一下方法:
_myTimer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(handleTimerAction:) userInfo:nil repeats:YES];
- timer的暂停;
[_timer setFireDate:[NSDate distantFuture]];
‘fireDate’ 是设置定时器的开启时间,通过将fireDate设置为distantFuture
(无限远的将来),将timer暂停。
3. 暂停后重启:
[_timer setFireDate:[NSDate distantPast]];
将fireDate设置为distantPast
,来将暂停后的timer重启。
4. timer销毁;
[_timer invalidate];
这一步非常重要,将timer从系统的runloop中移除,避免出现内存泄漏,并将timer的计时数据清零。
4. 格式化时间的样式,将计时时间与展示成00:00的样式;
+ (NSString *)stringWithTimeInterval:(NSTimeInterval)interval{ NSInteger min = interval/60; NSInteger sec = (NSInteger)interval%60; NSString *minStr =min<10? [NSString stringWithFormat:@"0%ld",(long)min]:[NSString stringWithFormat:@"%ld",(long)min]; NSString *secStr = sec <10 ?[NSString stringWithFormat:@"0%ld",(long)sec]:[NSString stringWithFormat:@"%ld",(long)sec]; return [NSString stringWithFormat:@"%@:%@",minStr,secStr];}
这里写了一个category,方便项目中其它地方的使用,简少代码的耦合;
我把项目上传到我的github上面了,有兴趣的朋友可以看一下,欢迎交流指正;
https://github.com/LINDreaming/DelibrateProject
效果图如下:
阅读全文
0 0
- NSTimer的使用(精简)
- IOS 定时器(NSTimer)的使用
- iOS 定时器(NSTimer)的使用
- NSTimer的使用
- NSTimer的使用
- NSTimer类的使用
- NSTimer的使用步骤
- NSTimer的使用
- NSTimer类的使用
- NSTimer的简单使用
- NSTimer的简单使用
- NSTimer的详细使用
- NSTimer类的使用
- NSTimer类的使用
- NSTimer的使用须知
- iOS NSTimer的使用
- NSTimer的使用
- NSTimer的使用须知
- 23种设计模式之——单例模式
- 玩过狼人杀吗
- IT行业、前端、java入门必备书籍
- usart&spi
- Unity—UI正对摄像机
- NSTimer的使用(精简)
- beibaowenti
- Binder机制和AIDL
- java上传与下载文件
- Linux总线设备驱动框架的理解
- WRK+fabric进行集群部署和压测
- 测试
- 【javascript】前端模块化的一些坑点
- 自动化测试流程图