2015-07-12 65 views
-1

我想要實現一個for循環,以便每次迭代時,它將在進入下一個循環之前等待一秒鐘。For循環與定時迭代 - Objective-C

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

這會否凍結主線程? – Lasonic

回答

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]; 
     } 
    }); 
} 
+0

可以說,這可能會更好,如果它採取了一個塊參數,並調用該塊,你有'/ do stuff'評論。這當然使它更加可重用。 – nhgrif

+2

@nhgrif無疑是如此,我只是不想將太多新的(對於OP)概念打包成一個答案;) – Leo