【问题标题】:adding delay between operations(obj c)在操作之间添加延迟(obj c)
【发布时间】:2017-09-19 00:27:01
【问题描述】:

我对 obj c 比较陌生,所以对于我的学校作业,我需要在(相同)函数中的三行执行之间添加延迟。有什么有利的选择吗?

line 1: [executing first operation];

line 2: Delay  /* I need to introduce delay here */

line 3: [executing second operation];

line 4: Delay  /* I need to introduce delay here again */

line 5: [executing second operation];

提前致谢,如有任何帮助,我们将不胜感激。

【问题讨论】:

  • 阅读 Grand Central Dispatch。
  • @rmaddy 你可以给我一个关于 gcd 的例子吗?
  • 搜索。你会发现很多例子。

标签: objective-c delay


【解决方案1】:

所以我找到的解决方案是:

[operation 1]
    double delayInSeconds = 9.3;
    dispatch_time_t popTime2 = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delayInSeconds * NSEC_PER_SEC));
    dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
        [operation 2];

double delayInSeconds2 = 9.3;
dispatch_time_t popTime2 = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delayInSeconds2 * NSEC_PER_SEC));
dispatch_after(popTime2, dispatch_get_main_queue(), ^(void){
   [operation 3];

 });

 });

这是正确的方法吗? 如果是的话,无论如何我不需要在操作 2 的延迟中嵌套操作 3

【讨论】:

    【解决方案2】:

    可以通过 NSRunLoop 方法实现目标 - (void)performSelector:(SEL)aSelector withObject:(nullable id)anArgument afterDelay:(NSTimeInterval)delay;

    [executing first operation];
    [self performSelector:@selector(2nd_Operation) withObject:nil 
     afterDelay:1st_Delay_In_Seconds];
    [self performSelector:@selector(3rd_Operation) withObject:nil 
     afterDelay:2nd_Delay_In_Seconds];
    

    请注意,如果将上述代码放在一种方法中,则两个延迟时间几乎同时开始。如果要说延迟 0.5s 后调用 2nd_operation 然后再延迟 0.5s 后调用 3rd_operation,那么 2nd_Delay_Time 应该是 0.5s+2nd_operation 执行时间+0.5s。如果您出于某种原因需要准确的延迟,我建议将最后一行放在 2nd_operation 的完整块中。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-03-03
      • 2021-10-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-01-14
      • 2017-09-18
      相关资源
      最近更新 更多