The following code is from the accepted answer of this post, regarding with implement search bar in table view with Core Data. It uses two fetched results controller (FRC). One for the "normal" table view, one for search results table view. And it uses a helper method to decide which FRC to use for table view data source methods, FRC delegate methods, etc..
I understand most of the code except the following part. What code should I put in to replace the comments "update the filter..."
? And why should I set the self.searchFetchedResultsController and its delegate to nil?
- (void)filterContentForSearchText:(NSString*)searchText scope:(NSInteger)scope
{
// update the filter, in this case just blow away the FRC and let lazy evaluation create another with the relevant search info
self.searchFetchedResultsController.delegate = nil;
self.searchFetchedResultsController = nil;
...
}
Here is what happens when you set the fetchedResultsController
to nil. The next time the table view (or search results table view) needs data, it will query its datasource
which in turn references the (non-existing) FRC. If you look into the fetchedResultsController
method you will see that the FRC is created lazily - only if it is . In the initialization routine, the fetch request is executed and a fresh result is made available to the data source. nil
While this works quite reliably, there is an argument to be made for not completely destroying the FRC. It is redundant and takes more time, CPU and battery power. The exact same effect can be achieved by simply calling
[fetchedResultsController performFetch:nil];
Now the data source will also have the newest data available.
EDIT
As stated in the comments you should really modify the fetchedResultsController
method to create lazily. Look at the Apple templates for guidance.
if (_fetchedResultsController != nil) {
return _fetchedResultsController;
}
// continue creating a new one