1.创建、开始、结束
NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(countDown:) userInfo:nil repeats:YES];
[timer fire];//开始
[timer invalidate];//停止(移除)
//其实创建后就会自动开始,所以在这里fire是没有用的,在repeats设为NO时,fire是可以启动timer
//销毁计时器,界面推出时移除,不然会循环引用造成内存泄漏
[timer invalidate];
timer = nil;
开启关闭计时器的方法
//关闭计时器
[timer setFireDate:[NSDate distantFuture]];//随机返回一个比较遥远的未来时间
//开启定时器
[timer setFireDate:[NSDate distantPast]];//随机返回一个过去的时间
例子
....
[self startCounting];
....
开始倒计时
- (void)startCounting
{
_getCodeButton.enabled = NO;
mCountDownNum=60;
[_getCodeButton setTitle:[NSString stringWithFormat:@"%d秒后重发",mCountDownNum] forState:UIControlStateNormal];
[_getCodeButton setTitleColor:RGBCOLOR(160, 160, 160) forState:UIControlStateNormal];
[_getCodeButton setBackgroundImage:[UIImage imageNamed:@"grayBtn_bg"] forState:UIControlStateNormal];
mTimer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(countDown:) userInfo:nil repeats:YES];
}
//计时
-(void)countDown:(NSTimer*)sender{
if (mCountDownNum>0) {
mCountDownNum--;
[_getCodeButton setTitle:[NSString stringWithFormat:@"%d秒后重发",mCountDownNum] forState:UIControlStateNormal];
}else if (mCountDownNum==0){
[mTimer invalidate];//停止
_getCodeButton.enabled = YES;
[_getCodeButton setTitle:@"获取验证码" forState:UIControlStateNormal];
[_getCodeButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
[_getCodeButton setBackgroundImage:[UIImage imageNamed:@""] forState:UIControlStateNormal];
_getCodeButton.backgroundColor = UIColorFromRGB(0x3caafa);
}
}
2.遇见的问题
button上的字跟着倒计时秒数一块跳动
解决方法:
_getCodeButton = [UIButton buttonWithType:UIButtonTypeCustom];//设为custom
3.[timer invalidate] 停止不了
//有时我们停止后发现timer还在继续运行,这时候有可能是timer多次注册了,自己可以在注册处打印看看。
如果多次注册,并且只有一次释放,则会造成内存泄漏。
解决方法:在注册代码前加上[timer invalidate] 这一句,无论是否已经注册先将它停止掉,这样应该就能解决了。
4**NSTimer在界面滑动时停止**
//加入到NSRunLoopCommonModes即可
[[NSRunLoop currentRunLoop] addTimer:timer forMode:NSRunLoopCommonModes];