rd42
rd42

Reputation: 3594

Why does this loop only run once?

Just want the screen to blink blue/red over and over for some time based on an odd or even condition, but it only runs once, instead of 30,000 times. What am I missing?

-(IBAction) changeBackgroundColor:(id)sender
{
    for (int y = 0; y < 30000; y++)
    {

    if(y % 2)
        {
            self.view.backgroundColor = [UIColor blueColor];
            colorView.backgroundColor = [UIColor redColor];  

        } else {

            self.view.backgroundColor = [UIColor redColor];
            colorView.backgroundColor = [UIColor blueColor];   
        }
    }
}

Upvotes: 0

Views: 313

Answers (3)

Abizern
Abizern

Reputation: 150625

If you are trying to get a blinking effect you could (and probably should) use Core Animation.

I answered a similar question here with example code.

Upvotes: 2

Jim Buck
Jim Buck

Reputation: 20726

You are "blinking" 30,000 times without ever returning to the iOS main system to give it a chance to display the results of your per blink. You need to blink once, return to iOS, come back, blink again, back to iOS, etc.

Upvotes: 5

Tommy
Tommy

Reputation: 100632

The loop runs 30000 times, but the screen is updated only once. You need to drop out to the runloop for changes to UIKit objects to take effect. Probably you want to set up an NSTimer and toggle the background colour within the callback.

Upvotes: 3

Related Questions