Reputation: 8967
So I have the following code for fetching all of my core data entities called Settings
- (NSFetchedResultsController *)fetchedResultsController {
if (fetchedResultsController_ != nil) {
return fetchedResultsController_;
}
/*
Set up the fetched results controller.
*/
// Create the fetch request for the entity.
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
// Edit the entity name as appropriate.
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Setting" inManagedObjectContext:self.managedObjectContext_];
[fetchRequest setEntity:entity];
[fetchRequest setReturnsObjectsAsFaults:NO];
[fetchRequest setResultType:NSManagedObjectResultType];
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"serviceName" ascending:NO];
NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:sortDescriptor, nil];
[fetchRequest setSortDescriptors:sortDescriptors];
// Edit the section name key path and cache name if appropriate.
// nil for section name key path means "no sections".
NSFetchedResultsController *aFetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:self.managedObjectContext_ sectionNameKeyPath:nil cacheName:nil];
aFetchedResultsController.delegate = self;
self.fetchedResultsController_ = aFetchedResultsController;
[aFetchedResultsController release];
[fetchRequest release];
return fetchedResultsController_;
}
I have a property of NSFetchedResultsController *fetchedResultsController
and I've been using it therough the app via:
[self.fetchedResultsController_ fetchedObjects]
The question is I want to fetch entities with a specific property, i.e: with a predicate:
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"%K == %@", @"settingName", somesettingName];
[fetchRequest setPredicate:predicate];
The question is should I create a new fetchResultsControllerWithServiceName: (NSString *) serviceName
or should I just use the existing method? What is the best practice for this?
Upvotes: 0
Views: 2531
Reputation: 31782
It's surely faster (though I'm not sure how much faster) to modify an existing fetch request controller rather than recreate it each time your predicate needs to be updated. Apple's documentation states clearly that "you should not use a cache if you are changing the fetch request", but since you aren't currently using caching, this is not an issue.
So, all you need to do to get updated results is update the predicate, call performFetch:
on the fetched results controller, and respond to the delegate callbacks you receive.
You may find it convenient to package up this series of calls into its own method, but you can certainly avoid regenerating the entire controller object when only the predicate is changing.
Upvotes: 1