-2

I have an app and I want to change the background color at increasingly fast rates. Basically, I want the background color to change after a three second delay, then a 2.9 second delay, etc....

So, what I thought was that I would make a random integer that I use to pick the random color (i.e. each integer corresponds to a color). This works fine, definitely no problems here. The problem is with the delays. I tried to do a bunch of things, but I can't wrap my head around the logic of it.

I apologize for not posting my code, but my code is very complicated right now and would take pages of context to understand (probably part of the problem). I am looking for a simple solution to this.

meda
  • 45,103
  • 14
  • 92
  • 122
John
  • 3
  • 5

2 Answers2

0

GCD has a method to dispatch a block after a delay:

dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(<#delayInSeconds#> * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        <#code to be executed after a specified delay#>
    });

You could wrap this into a recursive function that terminates at 0:

#define SECONDS_DECREMENT .1f

- (void)changeColorAfter:(float)seconds
{
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(seconds * NSEC_PER_SEC)), dispatch_get_main_queue(), ^
    {
        [self changeBackgroundToRandomColor];

        if (seconds > SECONDS_DECREMENT)
        {
            [self changeColorAfter:seconds - SECONDS_DECREMENT];
        }
    });
}
Jeff Holliday
  • 760
  • 6
  • 7
0

You could create a recursive function that calls itself every x amount of time. Something like this:

-(void)updateBackgroundWithInterval:(NSNumber *)interval {

    //Get the interval float value
    float intervalFloat = [interval floatValue];

    //Update your background and do whatever else

    NSLog(@"Hit interval = %.2f", intervalFloat);

    //Make your interval smaller
    intervalFloat -= 0.1;

    //Continue if the interval will be >= your minimum value (we'll say 0)
    if (intervalFloat > 0) {
        [self performSelector:@selector(updateBackgroundWithInterval:) withObject:@(intervalFloat) afterDelay:intervalFloat];
    }
}

Then, you can call it using something like this:

[self updateBackgroundWithInterval:@2.0];

I'd also recommend having a BOOL flag of some sort as an instance variable or property of the class that the updateBackgroundWithInterval: function checks each time, that way you can stop the process if the user exits the view, etc.

rebello95
  • 8,486
  • 5
  • 44
  • 65