Search code examples
iosobjective-cnsset

Getting a random object from NSSet doesn't work


Why am I not getting a random value from the list?

If I set the color manually like [UIColor redColor] just work fine.

- (id) init
 {
    self.color = [self randomColor]; //This doesn't work
    self.color = [UIColor someColor]; //This works
 }

- (UIColor *) randomColor {
    NSSet *colors = [NSSet setWithObjects:[UIColor redColor], [UIColor yellowColor], [UIColor orangeColor], nil];
    return [colors anyObject];
}

Solution

  • -anyObject does not return a random object. It's just difficult to predict which object it will return (most likely it's either the most efficient one to return, or the simplest to implement internally).