This may not be exactly how you implement this, but hopefully it will get you started.
Somewhere in your header or at the top of your implementation file:
#import <stdlib.h>
#import <time.h>
Elsewhere in your implementation:
//
// get count of entities
//
NSFetchRequest *myRequest = [[NSFetchRequest alloc] init];
[myRequest setEntity: [NSEntityDescription entityForName:myEntityName inManagedObjectContext:myManagedObjectContext]];
NSError *error = nil;
NSUInteger myEntityCount = [myManagedObjectContext countForFetchRequest:myRequest error:&error];
[myRequest release];
//
// add another fetch request that fetches all entities for myEntityName -- you fill in the details
// if you don't trigger faults or access properties this should not be too expensive
//
NSArray *myEntities = [...];
//
// sample with replacement, i.e. you may get duplicates
//
srandom(time(NULL)); // seed random number generator, so that you get a reasonably different series of random integers on each execution
NSUInteger numberOfRandomSamples = ...;
NSMutableSet *sampledEntities = [NSMutableSet setWithCapacity:numberOfRandomSamples];
for (NSInteger sampleIndex = 0; sampleIndex < numberOfRandomSamples; sampleIndex++) {
int randomEntityIndex = random() % myEntityCount; // generates random integer between 0 and myEntityCount-1
[sampledEntities addObject:[myEntities objectAtIndex:randomEntityIndex]];
}
// do stuff with sampledEntities set
If you need to sample without replacement, to eliminate duplicates, you might create an NSSet
of randomEntityIndex
NSNumber
objects, instead of just sampling random int
s.
In this case, sample from an ordered NSSet
, remove NSNumber
objects as you pull them out of the bag, and decrement myEntityCount
for the purposes of picking a random NSNumber
object from the set.