Skip to content

Instantly share code, notes, and snippets.

@winder
Created December 2, 2010 23:27
Show Gist options
  • Save winder/726312 to your computer and use it in GitHub Desktop.
Save winder/726312 to your computer and use it in GitHub Desktop.
Fetches a data set in pieces using limits and offsets.
#define kBatchSize 20
// This could take a while.
+ (void) recalculateAllStats {
MyAppDelegate *myAppDelegate = (MyAppDelegate *)
[[UIApplication sharedApplication] delegate];
NSManagedObjectContext *moc =
[myAppDelegate managedObjectContext];
NSEntityDescription *entity =
[NSEntityDescription entityForName:@"Entry"
inManagedObjectContext:moc];
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
[fetchRequest setEntity:entity];
// I need to look at all objects, so do not return faults.
[fetchRequest setReturnsObjectsAsFaults:NO];
[fetchRequest setFetchLimit:kBatchSize];
[fetchRequest setFetchOffset:0];
// Sort, in case Core Data doesn't enforce select order.
NSSortDescriptor *sorting =
[[NSSortDescriptor alloc]
initWithKey:@"Date" ascending:NO];
[fetchRequest setSortDescriptors:
[NSArray arrayWithObject:sorting]];
// Execute
NSError *error;
NSArray *items =
[moc executeFetchRequest:fetchRequest error:&error];
int i = 0;
int total = 0;
// Continue executing until 0 results are returned.
while ([items count] > 0) {
// Use the data here.
total += [items count];
// Update offset.
i = i + 1;
[fetchRequest setFetchOffset:kBatchSize * i];
items =
[moc executeFetchRequest:fetchRequest error:&error];
}
NSLog(@"Total = %d", total);
[sorting release];
[fetchRequest release];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment