Reputation:
I have a large number of objects in Core Data. Does the following only load what is needed for the UI as and when is needed or does it load all objects up front?
NSFetchedResultsController does have a fetchedObjects
property.. does it means it fetches everything upfront? What is the right way to fix this?
NSManagedObjectContext *context = # get from somewhere
NSManagedObjectModel *model = context.persistentStoreCoordinator.managedObjectModel;
NSDictionary *vars = @{...};
NSFetchRequest *fetchRequest = [model fetchRequestFromTemplateWithName:@"..."
substitutionVariables:vars];
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"..." ascending:NO];
NSArray *sortDescriptors = @[sortDescriptor];
fetchRequest.sortDescriptors = sortDescriptors;
NSFetchedResultsController *controller = [[NSFetchedResultsController alloc]
initWithFetchRequest:request
managedObjectContext:context
sectionNameKeyPath:nil
cacheName:@".."];
Upvotes: 4
Views: 602
Reputation: 119041
You generally shouldn't use fetchedObjects
. It will always be the full list of fetched objects, some of which may be in memory and some may be faults.
The whole point is that you want the FRC to load data (to fault objects) only as required. But, for it to do that, you need to tell it how much to load based on what your UI can display at any one time (the maximum number of items that could be on screen at the same time).
To do that you need to set the fetchBatchSize
on the NSFetchRequest
. Once you've done that the FRC will load a new 'page' of results (into memory) as required (when your UI is scrolled and new requests are made to the FRC for data).
Technically, it isn't the FRC that's doing this, it's the array object returned by the fetch which initially contains 'empty' objects and which transparently faults batches of objects on demand.
Upvotes: 1