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
In iOS, using Objective-C, is there a way to add such delays within a for loop, keeping in mind:
A code example within the context of a for loop would be most helpful. Thank you.
Use GCD dispatch_after.
You can search its usage on stackoverflow.
Nice article is here
Brief example in Swift for 1.5 seconds delay:
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, Int64(Double(NSEC_PER_SEC) * 1.5)), dispatch_get_main_queue()) {
// your code here after 1.5 delay - pay attention it will be executed on the main thread
}
and objective-c:
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^ {
// your code here after 1.5 delay - pay attention it will be executed on the main thread
});
This sounds like an ideal job for NSOperationQueue with the delay being implemented like this:
@interface DelayOperation : NSOperation
@property (NSTimeInterval) delay;
- (void)main
{
[NSThread sleepForTimeInterval:delay];
}
@end
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With