Search code examples
objective-cxcodeimageviewdidload

Why images are not randomizing?


I would like one of two images, apple sauce.jpg and 8292.jpg to appear when the app is first opened. However, I have opened the app several times and 8292.jpg always appears. Why is this and how can I fix it?

Here is my code:

- (void)viewDidLoad {

int randomimages = rand() % 2;

switch (randomimages) {
    case 0:
        imageview.image = [UIImage imageNamed:@"apple sauce.jpg"];
        break;
    case 1:
        imageview.image = [UIImage imageNamed:@"8292.jpg"];
        break;

    default:
        break;
}

theLabel.text = @"Submit it!";

   [super viewDidLoad];

}

Solution

  • You did not seed your random number generator:

    $ man 3 rand
    

    [...] If no seed value is provided, the functions are automatically seeded with a value of 1.

    Fix is easy: Insert this somewhere in your app startup process, for example in applicationDidFinishLaunching:.

    sranddev();