Search code examples
iphoneobjective-ciosnsset

NSSet how to extract object randomly?


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.


Solution

  • 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.