我想要實現一個for循環,以便每次迭代時,它將在進入下一個循環之前等待一秒鐘。For循環與定時迭代 - Objective-C
for (NSUInteger i = 0; i <=3; i++) {
//...do something
//...wait one second
}
我想要實現一個for循環,以便每次迭代時,它將在進入下一個循環之前等待一秒鐘。For循環與定時迭代 - Objective-C
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];
}
});
}
這會否凍結主線程? – Lasonic