您的位置:首页 > 移动开发 > IOS开发

iOS_NSTimer倒计时实例

2016-05-31 19:23 375 查看
这两天用到了,很久前封的一个NSTimer类,整理了下和小伙伴们一起分享下。

2016-09-09 NSTimer的补充

关于NSTimer的定义,官方给出解释是“A timer provides a way to perform a delayed action or a periodic action. The timer waits until a certain time interval has elapsed and then fires, sending a specified
message to a specified object. ” 翻译过来就是timer就是一个能在从现在开始的后面的某一个时刻或者周期性的执行我们指定的方法的对象。

而我们还应该注意, timer不是一种实时的机制,会存在延迟,而且延迟的程度跟当前线程的执行情况有关(比如大数据运算时)。

------------------------------------------------------------------------------------------

这里是核心代码:

<span style="font-family:Microsoft YaHei;font-size:14px;">//换算成倒计时时间
- (void)setTimeLabelbyday:(NSInteger)day andhour:(NSInteger)hour andmin:(NSInteger)min andsecond:(NSInteger)second{
self.lastTime=((day*24+hour)*60+min)*60+second;

self.str_Time=[NSString stringWithFormat:@"%02ld:%02ld:%02ld",self.lastTime/3600%24,self.lastTime/60%60,self.lastTime%60];

self.myTime=[NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(timeMove) userInfo:nil repeats:YES];
[[NSRunLoop mainRunLoop] addTimer:self.myTime forMode:NSRunLoopCommonModes];
}

//计时方法
- (void)timeMove{
if (self.lastTime==0) {
[self timeStop];
if (self.block_TimeUp) {
self.block_TimeUp();
}
}else{
//递减
self.lastTime--;
//新的字符串内容
lab.text = [NSString stringWithFormat:@"%02ld:%02ld:%02ld",self.lastTime/3600%24,self.lastTime/60%60,self.lastTime%60];
}
}

//开始倒计时
- (void)timeStart{
[self.myTime setFireDate:[NSDate distantPast]];
}

//停止倒计时
- (void)timeStop{
[self.myTime setFireDate:[NSDate distantFuture]];
}
</span>


demo链接:
倒计时demo (提取码:7896)

感谢观看,学以致用更感谢~
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  NSTimer 倒计时