NSTimer用法与问题1

来源:互联网 发布:域名哪里买 编辑:程序博客网 时间:2024/05/17 07:38

1.创建、开始、结束

NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(countDown:) userInfo:nil repeats:YES];     [timer fire];//开始    [timer invalidate];//停止//其实创建后就会自动开始,所以在这里fire是没有用的,在repeats设为NO时,fire是可以启动timer

例子

....[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只执行一次**

//timer只执行一次或没有执行的原因应该是因为他不在主线程里,加入到runLoop即可,可以加上如下代码[[NSRunLoop currentRunLoop] addTimer:timer forMode:NSRunLoopCommonModes];
1 0
原创粉丝点击