Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iPhone OS: Fetching a random entity instance using NSPredicate Nsfetchrequest and core data

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

like image 216
nickthedude Avatar asked May 13 '10 21:05

nickthedude


1 Answers

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];
like image 90
Corey Floyd Avatar answered Nov 15 '22 23:11

Corey Floyd