ios - 使dispatch_async内的NSTimer失效

标签 ios objective-c objective-c-blocks nstimer

我正在创建一个游戏,在游戏中我需要一个计时器。

我工作得很好,但是当我滚动 map 时它会停止,然后当我完成滚动时它会再次开始。我用dispatch_async修复了这个问题。这是代码

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{

                timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self  selector:@selector(timeNext) userInfo:nil repeats:NO];

                [[NSRunLoop currentRunLoop] addTimer:timer forMode:NSDefaultRunLoopMode];

                [[NSRunLoop currentRunLoop] run]; 
            });

计时器:

__block NSTimer *timer;

但是,如果应用程序进入后台,我需要停止这次(当它激活时,它会再次启动)。

通过这种方式,我可以滚动 map ,并且计时器运行良好,我尝试:

- (void)timeNext {
    [timer invalidate];
    }

但没有成功。有人知道如何阻止它吗?或任何其他想法来完成这项任务?

最佳答案

不要在全局队列的线程上创建计时器,然后在该线程上启动运行循环。

只需在主线程(主运行循环)上创建计时器,并将其添加到跟踪运行循环模式即可。定时器可以添加到多种运行循环模式。

timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self  selector:@selector(timeNext) userInfo:nil repeats:NO];
[[NSRunLoop currentRunLoop] addTimer:timer forMode:UITrackingRunLoopMode];

关于ios - 使dispatch_async内的NSTimer失效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16074489/

相关文章:

iphone - 如何确定为 Web 服务 API 实现的 Http 方法类型

ios - 如何允许选择和取消选择多个 UICollectionViewCell?

ios - 将 UIImage 的 NSData 表示形式转换为 NSImage

iphone - "Incompatible pointer to integer conversion"使用方 block 时

objective-c - 什么会导致 block 在 ARC 下不保留引用的 Objective-C 对象?

ios - ScrollView 上绘制的线条不是滚动的?

iOS : Transfer Scroll Gesture on a View to Another

objective-c - EventKit:提醒 dueDateComponents 与 Alarm

objective-c - 在 OSx 中模拟/发送修饰键(Ctrl、Alt、fn、Shift)

objective-c - -[NSInvocation retainArguments] 是否复制 block ?