For循环与定时迭代 - Objective-C

问题描述:

我想要实现一个for循环,以便每次迭代时,它将在进入下一个循环之前等待一秒钟。For循环与定时迭代 - Objective-C

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

这会否冻结主线程? – Lasonic

您可以使用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]; 
     } 
    }); 
} 
+0

可以说,这可能会更好,如果它采取了一个块参数,并调用该块,你有'/ do stuff'评论。这当然使它更加可重用。 – nhgrif

+2

@nhgrif无疑是如此,我只是不想将太多新的(对于OP)概念打包成一个答案;) – Leo