具有定时迭代的 For 循环 - Objective-C

For loop with timed iterations - Objective-C

我想实现一个 for 循环,这样对于每次迭代,它会在进入下一个之前等待整整一秒钟。

for (NSUInteger i = 0; i <=3; i++) {
   //...do something
   //...wait one second
}

您可以使用dispatch_after来避免在等待时阻塞主线程:

- (void)loopAndWait:(NSUInteger)currentIndex maxIndex:(NSUInteger)maxIndex {
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 1 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
        // do stuff
        NSUInteger nextIndex = currentIndex + 1;
        if (nextIndex <= maxIndex) {
            [self loopAndWait:nextIndex maxIndex:maxIndex];
        }
    });
}