循环中所有值的延迟

Delay for all value in loop

在延迟 5 秒后点击按钮后,将执行数组中的总值。

- (IBAction)testButton:(id)sender {
NSArray *array = [NSArray arrayWithObjects:
                      @"Hefeweizen", @"IPA", @"Pilsner", @"Stout", nil];


for (NSIndexPath *anIndexPath in array) {




        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 5 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{


             NSLog(@"INDEX PATH %@",anIndexPath);



        }); 
}

如何为数组中的每个值创建 5 秒(给定)的延迟?

试试这个代码,我添加了一个递增的延迟,但我不确定这是否是一个健康的方法。无论如何,对于小循环来说应该不是问题:

- (IBAction)testButton:(id)sender {
    NSArray *array = [NSArray arrayWithObjects:
                      @"Hefeweizen", @"IPA", @"Pilsner", @"Stout", nil];

    int64_t delayInSeconds = 5.0;

    for (NSIndexPath *anIndexPath in array)
    {

        dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC);

        dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
            NSLog(@"INDEX PATH %@",anIndexPath);
        });
        delayInSeconds += 5;
    }
}

当您遍历数组时,您的 dispatch_after() 调用将在非常短的时间内发生,因此它们与 NSLog() 的块稍后也会在几乎相同的时间执行.

根据您要实现的目标和所需的精度,您可以做一些简单的事情,例如在迭代数组时将每个块安排在 5 秒后:

int64_t interval = 0;
for (NSIndexPath *anIndexPath in array) {
    dispatch_time_t start = DISPATCH_TIME_NOW;
    interval += 5;
    dispatch_after(dispatch_time(start, interval * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
        NSLog(@"INDEX PATH %@",anIndexPath);
    }); 
}

在此示例中,第一个块将在 5 秒内安排,第二个块将在 10 秒内安排,第三个块将在 15 秒内安排,依此类推。

您可以轻松地一个接一个地排队执行:

- (void)executeFirstInArray:(NSArray *)array {
   NSString *firstItem = [array firstObject];
   array = [array subarrayWithRange:NSMakeRange(1, array.count - 1)];

   NSLog(@"Item: %@", firstItem);

   if (array.count > 0) {
      [self performSelector:_cmd withObject:array afterDelay:5.0];
   }
}

- (IBAction)testButton:(id)sender {
    NSArray *array = [NSArray arrayWithObjects:
                   @"Hefeweizen", @"IPA", @"Pilsner", @"Stout", nil];

   [self performSelector:@selector(executeFirstInArray:) withObject:array afterDelay:5.0];
}