0

I've created code, so: when the view did load, show up a random image. I've written some code, but it always starts with the same image (and viewbgcolor)..

my code:

-(void)viewDidLoad
{
    index = [NSNumber numberWithInt:(([index intValue] + 1) % 6)];
    switch ([index intValue]) {
        case 0:
            moodImage.image = [UIImage imageNamed:@"angry.png"];
            self.view.backgroundColor = [UIColor redColor];
            break;

        case 1:
            moodImage.image = [UIImage imageNamed:@"Disappointed.png"];
            self.view.backgroundColor = [UIColor brownColor];
            break;

        case 2:
            moodImage.image = [UIImage imageNamed:@"glad.png"];
            self.view.backgroundColor = [UIColor orangeColor];
            break;
        case 3:
            moodImage.image = [UIImage imageNamed:@"happy.png"];
            self.view.backgroundColor = [UIColor yellowColor];
            break;

        case 4:
            moodImage.image = [UIImage imageNamed:@"sad.png"];
            self.view.backgroundColor = [UIColor grayColor];
            break;

        case 5:
            moodImage.image = [UIImage imageNamed:@"surprised.png"];
            self.view.backgroundColor = [UIColor greenColor];
            break;
    }
}

This is really frustrating.. It works well with an IBAction, but not with the viewdidload... Has someone a alternative block of code to let this work?

Matthias Bauch
  • 89,811
  • 20
  • 225
  • 247

2 Answers2

2
index = [NSNumber numberWithInt:(([index intValue] + 1) % 6)];

There is no random value in this line of code.

Try this:

index = [NSNumber numberWithInt:arc4random_uniform(5)];

See "Generating Random Numbers in Objective-C" for info about random numbers in objective-c

Community
  • 1
  • 1
Matthias Bauch
  • 89,811
  • 20
  • 225
  • 247
0

Instead of

[NSNumber numberWithInt:(([index intValue] + 1) % 6)]

Use

 arc4random(5)

You need to form random value for each viewDidCall, and from your code it doesn't happen.

Documentation for arc4random()

Anoop Vaidya
  • 46,283
  • 15
  • 111
  • 140