NSTimer的使用(精简)

简述:NSTimer是iOS系统的计时控件,下面介绍NSTimer的使用,简单详细:

这里写图片描述

  1. 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];
  1. 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
效果图如下:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值