Sarabyte Studios Sarabyte Studios - 4 years ago 78
iOS Question

How to add a delay to a loop?

Im attempting add image views to a UIView using this code:

for (int i = 0; i <numberOfImages; i++) {
UIImageView *image = [UIImageView alloc]initWithFrame:CGRectMake(40, 40, 40, 40)];
image.image = [images objectAtIndex:i];
[self.view addSubview:image];
}


This works but the problem is I would like to have a 5 second delay before it adds each image, instead it adds them all at the same time. Can anybody help me out? Thanks.

Example:

5 seconds = one image on screen
10 seconds = two images on screen
15 seconds = three images on screen

Sid Sid
Answer Source

It will be more efficient to use an NSTimer.

NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:numberOfSeconds
                                                      target:self 
                                                    selector:@selector(methodToAddImages:) 
                                                    userInfo:nil 
                                                     repeats:YES];

This will essentially call methodToAddImages repeatedly with the specified time interval. To stop this method from being called, call [NSTimer invalidate] (bear in mind that an invalidated timer cannot be reused, and you will need to create a new timer object in case you want to repeat this process).

Inside methodToAddImages you should have code to go over the array and add the images. You can use a counter variable to track the index.

Another option (my recommendation) is to have a mutable copy of this array and add lastObject as a subview and then remove it from the mutable copy of your array.

You can do this by first making a mutableCopy in reversed order as shown:

NSMutableArray* reversedImages = [[[images reverseObjectEnumerator] allObjects] mutableCopy];

Your methodToAddImages looks like:

- (void)methodToAddImages
{
    if([reversedImages lastObject] == nil)
    {
        [timer invalidate];
        return;
    }

    UIImageView *imageView = [[UIImageView alloc] initWithFrame:(CGRectMake(40, 40, 40, 40))];
    imageView.image = [reversedImages lastObject];
    [self.view addSubview:imageView];
    [reversedImages removeObject:[reversedImages lastObject]];
}

I don't know if you're using ARC or Manual Retain Release, but this answer is written assuming ARC (based on the code in your question).

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download