0

Once the button is tapped after a delay of 5 seconds the total values in the array gets executed.

- (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);



        }); 
}

How to create delay of 5 sec (given) for every value inside the array ?

Ramanan R R
  • 896
  • 8
  • 18

3 Answers3

2

When you iterate over the array, your dispatch_after() calls will happen in a very short time frame, so their blocks with the NSLog() will later be executed at pretty much the same time as well.

Depending on what you are trying to achieve and the precision you need, you could do something as simple as scheduling each block 5 sec later at the time when you iterate over the array:

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);
    }); 
}

In this example, the first block will be scheduled in 5 sec, the second in 10 sec, the third in 15 sec, and so on.

puzzle
  • 6,071
  • 1
  • 25
  • 30
2

You can easily queue the execution one after another:

- (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];
}
Sulthan
  • 128,090
  • 22
  • 218
  • 270
1

Try this code, I added a incrementing delay, but I'm not sure if this is a healthy approach. Anyways, It shouldn't be a problem for small loops :

- (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;
    }
}
ShahiM
  • 3,179
  • 1
  • 33
  • 58