Changing the Sorting in an NSFetchedResultsController on the fly

aleclerc picture aleclerc · Nov 11, 2009 · Viewed 12k times · Source

I'm trying to change the sorting in a NSFetchController on the fly, by some sort of segmented control. To either sort A->Z Z->A type thing.

What do I have to do to do this? I'm following Jeff Lamarche's example here: Here

Do I need to make a new NSFetchedResultsController and then set it, or do I just make a new NSFetchRequest and do

fetchedResultController.fetchRequest = newFetchRequest

and then my table will automatically update?

Answer

Andreas Schaefer picture Andreas Schaefer · Sep 12, 2010

I was stuck with the same problem and I could fix it with just setting the sort descriptors on the FetchRequestController's FetchRequest, then execute a fetch (performFetch) and finally reload the data on the table view.

NSArray *sortDescriptors = [NSArray arrayWithObject: sorter];
[[fetchedResultsController fetchRequest] setSortDescriptors:sortDescriptors];
NSError *error;
if (![[self fetchedResultsController] performFetch:&error]) {
        // Handle you error here
}
[sorter release];
[myTableView reloadData];

This was the easiest way for me to deal with the change the sorting on the fly without dropping the FRC or do any other fancy object handling. I am not sure about the performance implications on that and it could have an impact if the set of rows in the table is huge.