在延迟5秒后点击按钮后,数组中的总值将被执行。
- (IBAction)testButton:(id)sender {
NSArray *array = [NSArray arrayWithObjects:
@"Hefeweizen", @"IPA", @"Pilsner", @"Stout", nil];
for (NSIndexPath *anIndexPath in array) {
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 5 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
NSLog(@"INDEX PATH %@",anIndexPath);
});
}
如何为数组内的每个值创建5秒(给定)的延迟?
答案 0 :(得分:2)
当您遍历数组时,您的dispatch_after()调用将在非常短的时间内发生,因此它们的NSLog()块将在几乎同时执行。
根据您要实现的目标和所需的精度,您可以做一些简单的事情,比如在迭代数组时5秒后安排每个块:
int64_t interval = 0;
for (NSIndexPath *anIndexPath in array) {
dispatch_time_t start = DISPATCH_TIME_NOW;
interval += 5;
dispatch_after(dispatch_time(start, interval * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
NSLog(@"INDEX PATH %@",anIndexPath);
});
}
在这个例子中,第一个区块将在5秒内安排,第二个区块将在10秒内安排,第三个区块将在15秒内安排,依此类推。
答案 1 :(得分:2)
您可以轻松地逐个排队执行:
- (void)executeFirstInArray:(NSArray *)array {
NSString *firstItem = [array firstObject];
array = [array subarrayWithRange:NSMakeRange(1, array.count - 1)];
NSLog(@"Item: %@", firstItem);
if (array.count > 0) {
[self performSelector:_cmd withObject:array afterDelay:5.0];
}
}
- (IBAction)testButton:(id)sender {
NSArray *array = [NSArray arrayWithObjects:
@"Hefeweizen", @"IPA", @"Pilsner", @"Stout", nil];
[self performSelector:@selector(executeFirstInArray:) withObject:array afterDelay:5.0];
}
答案 2 :(得分:1)
试试这段代码,我添加了一个递增延迟,但我不确定这是否是一种健康的方法。无论如何,小循环应该不是问题:
- (IBAction)testButton:(id)sender {
NSArray *array = [NSArray arrayWithObjects:
@"Hefeweizen", @"IPA", @"Pilsner", @"Stout", nil];
int64_t delayInSeconds = 5.0;
for (NSIndexPath *anIndexPath in array)
{
dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC);
dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
NSLog(@"INDEX PATH %@",anIndexPath);
});
delayInSeconds += 5;
}
}