One way to fetch a random row from a CoreData entity

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

#import stdlib.h

for it) to just pick out an appropriate random index, and then set that in an NSPredicate like this:

NSFetchRequest *request = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Item" inManagedObjectContext:managedObjectContext];
[request setEntity:entity];
        // 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];
[request setPredicate:predicate];
[request setFetchLimit:1];
NSError *error = nil;
NSArray *results = [managedObjectContext executeFetchRequest:request error:&error];