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
Instead use the fetchLimit in conjunction with the fetchOffset that way you can efficiently fetch only a single entity into memory:
NSFetchRequest *myRequest = [[NSFetchRequest alloc] init];
[myRequest setEntity: [NSEntityDescription entityForName:myEntityName inManagedObjectContext:myManagedObjectContext]];
NSError *error = nil;
NSUInteger myEntityCount = [myManagedObjectContext countForFetchRequest:myRequest error:&error];
NSUInteger offset = myEntityCount - (arc4random() % myEntityCount);
[myRequest setFetchOffset:offset];
[myRequest setFetchLimit:1];
NSArray* objects = [myManagedObjectContext executeFetchRequest:myRequest error:&error];
id randomObject = [objects objectAtIndex:0];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With