For循环与定时迭代 - Objective-C
问题描述:
我想要实现一个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