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

Las*_*nic -1 iteration objective-c

我想实现一个for循环,这样对于每次迭代,它将等待一秒钟才能进入下一个循环.

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

Leo*_*Leo 5

您可以使用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];
        }
    });
}
Run Code Online (Sandbox Code Playgroud)

  • 毫无疑问,@ nhgrif,我只是不想将太多新的(对于OP)概念打包成一个答案;) (2认同)