I am not sure about how NSSet's anyObject work. What does it mean that "The object returned is chosen at the set’s convenience" (from the NSSet class reference) ? 
Further, how can I best extract objects randomly from a NSSet? I was thinking about getting allObjects in an array and then myArray[arc4random_uniform(x)] where x is the number of objects in the array.
Quote from NSSet Class Reference:
The object returned is chosen at the set’s convenience—the selection is not guaranteed to be random.
For "randomness", convert the NSSet to an NSArray using [theSet allObjects].
Next, pick any object randomly using arc4random_uniform().
Usually, NSSet instances are created with a CFHash backing, so they almost always return the first object in that hash, as it is the fastest to look up. The reason it says 
The object returned is chosen at the set’s convenience—the selection is not guaranteed to be random.
Is because you don't always know it will have a backing array. For all you know, the NSSet instance you have has a NSDictionary backing it, or some other similar data structure.
So, in conclusion, if you need a random object from a NSSet, don't use -anyObject, instead  use allObjects: and then shuffle that array.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With