Search code examples
objective-carc4random

Issue calling objectAtIndex method to get random color


Beginner to objective-c, so please excuse basic mistakes.

Goal is to set predictionLabel.textColor to a random color from an array.

// fill array colors
self.colors = @[@"redColor", @"greenColor", @"blueColor", @"greyColor", @"orangeColor", @"purpleColor"];

// get random number based on array count
int randomColor = arc4random_uniform(self.colors.count);

// set predictionLabel.textColor to random color
self.predictionLabel.textColor = [UIColor [self.colors objectAtIndex:randomColor]];

I keep getting the error message "Expected identifier" at [UIColor [self.colors.

Being new, I'm having a hard time troubleshooting this one. Any advice?


Solution

  • You're not using Key Value Coding, though you want to. You're really just guessing about the method names that might be on UIColor. Why not use an array of UIColor objects instead of the names of the class methods. Like this:

    self.colors = @[[UIColor redColor], [UIColor greenColor], [UIColor blueColor], [UIColor grayColor], UIColor orangeColor], [UIColor purpleColor]];
    
    // get random number based on array count
    int randomColor = arc4random_uniform(self.colors.count);
    
    // set predictionLabel.textColor to random color
    self.predictionLabel.textColor = [self.colors objectAtIndex:randomColor];
    

    Also, watch the spelling of "grey" vs "gray". [UIColor greyColor] doesn't exist.