Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 689
ticofab Avatar asked Jun 27 '12 20:06

ticofab


2 Answers

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().

like image 186
Anne Avatar answered Sep 21 '22 05:09

Anne


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.

like image 32
Richard J. Ross III Avatar answered Sep 20 '22 05:09

Richard J. Ross III