The problem with fetching n
objects one by one could be performance. Depending on how large n
is, this might not scale.
Instead, you could take advantage of the fact that Core Data is pretty efficient when handling large number of objects. You could fetch tens of thousands of objects without too large a memory footprint due to a mechanism called "faulting".
Thus, i would suggest that you fetch all objects and simply pick some out from the result.
NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Response"];
NSArray *all = [managedObjectContext executeFetchRequest:request error:nil];
NSMutableArray *pickedAnswers = [NSMutableArray array];
int remaining = 10;
if (all.count < remaining) { /* abort */ }
while (remaining > 0) {
Response *response = all[arc4random_uniform(all.count)];
if (![pickedAnswers containsObject:response]) {
[pickedAnswers addObject:response];
remaining--;
}
}
Note that another elegant answer would be to first shuffle the array (as shown here and then pick the first n
elements). That would eliminate unnecessary runs through the while
loop.