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

iOS-NSTimer在用户操作tableView时暂停的问题。

2016-01-09 00:00 246 查看
最近客户电商类产品提了一个新的需求,限时领取,主要功能就是一个类似京东淘宝的抢购功能,其中有一个需求是在主界面显示当前抢购的倒计时。

这个功能我是用UITableViewCell实现的,关于NSTimer销毁的逻辑代码都已经写完,在自己测试时发现当操作UITableView时,NSTimer会失效,当抬起手指后NSTimer继续执行。

这样就有一个很严重的问题,就是当我按下的时候,限时领取显示的倒计时不会更新,当我抬起手指对当前界面无操作时才会有更新。

查看了相关博客和官方文档后,原来NSTimer原来是和当前RunLoop一起工作的,我将NSTimer加入到RunLoop中后却出现了另一个错误,这个错误的引起是因为我在主线程里调用了runloop对象的run方法,引起了死锁。

_timer =[NSTimer scheduledTimerWithTimeInterval:1 target:self
selector:@selector(timerRun) userInfo:nil repeats:YES];
NSLog(@"begin");
[[NSRunLoop currentRunLoop] addTimer:_timer forMode:NSDefaultRunLoopMode];
[[NSRunLoop currentRunLoop] run];

所以我在异步线程里调用了这个方法,代码如下:

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{

_timer =[NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(timerRun) userInfo:nil repeats:YES];
NSLog(@"begin");
[[NSRunLoop currentRunLoop] addTimer:_timer forMode:NSDefaultRunLoopMode];
[[NSRunLoop currentRunLoop] run];
});

在另一个线程中将NSTimer添加到RunLoop中,果然解决了这个问题。

因为是在子线程里调用的timer执行的方法,所以别忘了用performSelectorOnMainThread更新UI。

另附源码

https://github.com/youkennkyou/LimitTimeReceiveDemo
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  iOS NSTimer NSRunLoop