如何在响应用户交互时运行重复的NSTimer或计划进程

时间:2012-07-02 07:57:58

标签: ios nstimer background-process

当我使用

[NSTimer scheduledTimerWithTimeInterval:intervalCountDownTimer target:self selector:@selector(updateCountDownDurationForTimer:) userInfo:nil repeats:YES];

如果我滚动UITableView,它会暂停。只有在滚动停止后才会恢复。

我的tableView使用dispatch_async & dispatch_sync异步加载图像,我不确定这是否是主要原因。

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{

            FXDMediaItem *mediaItem = [self mediaItemAtIndexPath:indexPath];

            if (mediaItem) {
                dispatch_sync(dispatch_get_main_queue(), ^{
                    cell.imageviewAlbumArt.image = [mediaItem albumArtImage];
                });
            }
        });

我一直在寻找在后台模式下运行此计时器的方法,但找不到合适的解决方案。它不一定是NSTimer,但我需要使用预定的重复过程

我怀疑答案实际上可能很简单,但找不到它

3 个答案:

答案 0 :(得分:6)

这里的问题是通过使用scheduledTimerWithTimeInterval创建计时器:target:selector:userInfo:repeats:在默认模式下将其添加到主运行循环中。滚动UITableView(实际上是UIScrollView)时,这似乎暂停了。这里的技巧是使用不同的模式将您的计时器添加到主运行循环,如下所示:

timer = [NSTimer timerWithTimeInterval:intervalCountDownTimer target:self selector:@selector(updateCountDownDurationForTimer:) userInfo:nil repeats:YES];
[[NSRunLoop mainRunLoop] addTimer:timer forMode:NSRunLoopCommonModes];

答案 1 :(得分:0)

如果您已经在使用GCD进行后台工作,请尝试将updateCountDownDurationForTimer:内的内容放在后台线程中。

答案 2 :(得分:0)

至于你的计时器,你看过dispatch_source_create()吗?

我假设您正在更新标签或其他内容,对吧?在表格视图滚动时更新-scrollViewDidScroll:中的标签,保留计时器,而不是。

如果我对自己的假设有误,请在计时器上发布一些代码,我会相应更新我的答案。