
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
1 | #import stdlib.h |
for it) to just pick out an appropriate random index, and then set that in an NSPredicate like this:
1 2 3 4 5 6 7 8 9 | 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]; |
Easy!
Leave a comment on One way to fetch a random row from a CoreData entity
RSS feed for comments on this post · TrackBack URI