ios - 如何在后台线程中运行 NSTimer

标签 ios nstimer

我想使用 BackGround thread 运行 NSTimer 因为我已经写了下面的代码但是我的 NSTimer 方法没有被调用!

有人能帮帮我吗

- (void)viewDidLoad {
       [super viewDidLoad];
       // Do any additional setup after loading the view.
        NSOperationQueue* operationQueue = [[NSOperationQueue alloc] init];
        [operationQueue addOperationWithBlock:^{
        // Perform long-running tasks without blocking main thread

        [NSTimer scheduledTimerWithTimeInterval:2
                                                 target:self
                                               selector:@selector(targetMethod)
                                               userInfo:nil
                                                repeats:YES];
          }];
}

-(void)targetMethod{
         NSLog(@"Timer Called");
}

最佳答案

您可以为后台线程使用 GCD 调度队列 :=

 dispatch_async(dispatch_get_global_queue( DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^(void)
                   {
                       NSTimer *timer = [NSTimer timerWithTimeInterval:0.5
                                                                target:self
                                                              selector:@selector(timerFired)
                                                              userInfo:nil repeats:YES];
                       [[NSRunLoop mainRunLoop] addTimer:timer forMode:NSRunLoopCommonModes];
                       dispatch_async(dispatch_get_main_queue(), ^(void)
                                      {
                                      });
                   });

关于ios - 如何在后台线程中运行 NSTimer,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41483550/

相关文章:

ios - NSTimer "target": How to reference a method of a class?

iphone - 当应用程序进入后台并返回时,我的 NSRunLoop 和计时器会发生什么情况?

iphone - 当我的应用程序进入后台模式时,如何更新位置管理器和计时器?

ios - Heroku 和 MongoDb 上的自定义解析服务器错误 3080 : JSON text did not start with array or object and option to allow fragments not set

iphone - 获取打印预览并将其保存为 PDF 文件

ios - 禁用 GSM 调用、SMS、MMS 并保持 GSM 调制解调器启用?

ios - 当 slider 按钮超过最大值的大约 60% 时,UISlider 最大轨道图像使用最小轨道图像

crash - NSTimer 错误访问

ios - 为什么对象在 NSTimer 失效后重置?

ios - 如何为多个不同的 Controller 制作 NSTimer? swift