ios 定时器timer

来源:互联网 发布:文武学校 知乎 编辑:程序博客网 时间:2024/06/06 10:03

模拟场景:点击获取验证码。

1.点击关闭按钮的交互:避免再次点击促发子线程
button.userInteractionEnabled = NO;
2.开启子线程(NSThread,dispatch,GCD)
这里用NSThread:
[NSThread detachNewThreadSelector:@selector(test) toTarget:self withObject:nil];
3.方法test里的代码
-(void)test
{
@autoreleasepool {

    self.timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(sendVertifyCode:) userInfo:nil repeats:YES];    [[NSRunLoop currentRunLoop]run];}

}
4.按钮标题的更换
static int _index = 60;
- (void)sendVertifyCode:(NSTimer*)timer
{

//这里要进行一些判断,设置按钮的标题,index为0 的时候打开交互,index重置为60,定时器停止。

index–;

}

注意:test方法里面创建自动释放是应为NSThread开启的子线程不会隐形创建自动释放池,导致timer对象无法得到释放,所以必须手动创建自动释放池。如果是GCD和dispathc就不用。

0 0
原创粉丝点击