在不阻塞UI的情况下在For循环中添加延迟 [英] Adding Delay In A For Loop Without Blocking UI
问题描述
在我的用户界面中,点击一个按钮时,它会调用一个for循环,该循环依次执行多个任务.
In my UI, when a button is tapped, it calls a for loop that executes several tasks sequentially.
// For Loop
for (int i = 1; i <= 3; i++)
{
// Perform Task[i]
}
// Results:
// Task 1
// Task 2
// Task 3
在每个任务之后,我想添加一个用户定义的延迟.例如:
After each task, I would like add a user-defined delay. For example:
// For Loop
for (int i = 1; i <= 3; i++)
{
// Perform Task[i]
// Add Delay Here
}
// Results:
//
// Task 1
// Delay 2.5 seconds
//
// Task 2
// Delay 3 seconds
//
// Task 3
// Delay 2 seconds
在iOS中,使用Objective-C,有一种方法可以在for循环中添加此类延迟,请记住:
In iOS, using Objective-C, is there a way to add such delays within a for loop, keeping in mind:
- 用户界面应保持响应状态.
- 必须按顺序执行任务.
在for循环上下文中的代码示例将是最有帮助的.谢谢.
A code example within the context of a for loop would be most helpful. Thank you.
推荐答案
此解决方案是否有效?我没有使用dispatch_after,而是使用带有[NSThread sleepForTimeInterval]块的dispatch_async,这使我可以在自定义队列中的任何所需位置放置延迟.
Would this solution work? Instead of using dispatch_after, I use dispatch_async with a [NSThread sleepForTimeInterval] block, which allows me to put a delay anywhere that I need in my custom queue.
dispatch_queue_t myCustomQueue;
myCustomQueue = dispatch_queue_create("com.example.MyQueue", NULL);
dispatch_async(myCustomQueue, ^ {
NSLog(@"Task1");
});
dispatch_async(myCustomQueue, ^ {
[NSThread sleepForTimeInterval:2.5];
});
dispatch_async(myCustomQueue, ^ {
NSLog(@"Task2");
});
dispatch_async(myCustomQueue, ^ {
[NSThread sleepForTimeInterval:3.0];
});
dispatch_async(myCustomQueue, ^ {
NSLog(@"Task3");
});
dispatch_async(myCustomQueue, ^ {
[NSThread sleepForTimeInterval:2.0];
});
这篇关于在不阻塞UI的情况下在For循环中添加延迟的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!