Working on an app where I have a large collections of managed objects against which I want to fetch a few random instances.
My question is, is there any way I can use NSPredicate and NSFetchRequest to return several objects at random.
I saw that you could actually add a NSFetchRequest into the entity using the data modeler, any way to do the random fetch using this?
Also what would be the best method for determining the “count” of a table so I can set the bounds of the random number generator.
let me know if you need more details.
Thanks!
Nick
This may not be exactly how you implement this, but hopefully it will get you started.
Somewhere in your header or at the top of your implementation file:
Elsewhere in your implementation:
If you need to sample without replacement, to eliminate duplicates, you might create an
NSSetofrandomEntityIndexNSNumberobjects, instead of just sampling randomints.In this case, sample from an ordered
NSSet, removeNSNumberobjects as you pull them out of the bag, and decrementmyEntityCountfor the purposes of picking a randomNSNumberobject from the set.