I spent a little time looking around for a way to get a random row out of a CoreData entity, and I didn’t find too much, so I’ll post about it here. In my entity (let’s call it “Items”), there are 198 objects stored. I have a non-alphabetical Decimal “siteOrder” attribute that helps me sort by a canonical order dependent on its original source. Because I have this decimal attribute already, I can take advantage of it by using arc4random() (don’t forget to
for it) to just pick out an appropriate random index, and then set that in an NSPredicate like this:
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Item" inManagedObjectContext:managedObjectContext];
// Assumes that you know the number of objects per entity, and that your order starts at zero.
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"siteOrder = %d", arc4random() % kNumItems];
NSError *error = nil;
NSArray *results = [managedObjectContext executeFetchRequest:request error:&error];