【问题标题】:dispatch_once invalidate the NSTimerdispatch_once 使 NSTimer 无效
【发布时间】:2014-07-15 06:46:12
【问题描述】:

这是我的示例代码..我每秒钟都有一个计时器来触发函数“调用”。

NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(call:) userInfo:[NSDictionary dictionaryWithObjectsAndKeys:@"sdfsf",@"wsdf", nil] repeats:YES];


-(void)call :(NSTimer *)timer{
    NSLog(@"called outside %@",timer.userInfo);
   static dispatch_once_t myDisPatch;
    dispatch_once(&myDisPatch, ^{
        NSLog(@"called inside");
    });

}

我的疑问是,当我们将“static dispatch_once_t myDisPatch”更改为“dispatch_once_t myDisPatch”时。然后计时器自动失效。它不会再次调用该函数。为什么当我从 dispatch_once_t 中删除 static 关键字时会发生这种情况?为什么它会停止计时器?提前致谢。

【问题讨论】:

    标签: objective-c ios7 grand-central-dispatch nstimer


    【解决方案1】:

    代码不会停止您的计时器。相反,当您删除 static 关键字时,它会在等待陷阱中阻塞主线程(它会永远停留在这里)。

    当您希望计时器被触发时,在调试器中单击暂停,您将看到堆栈跟踪。

    如果您不想使用静态调度令牌,请将其赋值为 0(不知道为什么您实际上需要 dispatch_once)

    dispatch_once_t myDisPatch = 0;
    dispatch_once(&myDisPatch, ^{
        NSLog(@"called inside");
    });
    

    【讨论】:

      【解决方案2】:
      static dispatch_once_t myDisPatch;
      dispatch_once(&myDisPatch, ^{
          NSLog(@"called inside");
      });
      

      这是通常用于单例的代码,以确保它只执行一次。当您删除static 时,它可以多次执行,这就是它起作用的原因。您根本不应该将它用于重复计时器。

      所以对于静态,您每秒都会看到“被调用的外部”,但“被调用的内部”只有一次。这并不意味着计时器已停止。

      【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多