19

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?

aleclerc
  • 707
  • 2
  • 7
  • 11

4 Answers4

33

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.

  • I used your solution. It seems to have no lag. But does any body know if this will do a physical fetch from the database? – user523234 Apr 14 '13 at 00:04
  • 2
    Be aware that changing sortDescriptors on instantiated FRC's fetchRequest has one downside. When using delegate method `controller:didChangeObject:atIndexPath:forChangeType:newIndexPath:` FRC reports object as 'moved' rather than 'updated' when, as docs states, `the changed attribute on the object is one of the sort descriptors used in the fetch request`. FRC makes note of that keypaths only on its instantiation, so when you later change sortDescriptors to other keypaths, FRC will not take it into account and will report 'updates' instead of 'moves' or vice versa. Better make new FRC. – bteapot May 27 '15 at 15:17
  • during moved you can assume update too, just use case fallthrough – malhal Jul 11 '20 at 13:00
7

Instead of using your NSFetchedResultsController as your table view data source, create an NSArray that you set when the user changes sort order with your segmented control basing the array contents on the fetched results. Then just sort using standard array sorting. Something like this:

- (IBAction)segmentChanged:(id)sender
{
    // Determine which segment is selected and then set this 
    // variable accordingly
    BOOL ascending = ([sender selectedSegmentIndex] == 0);

    NSArray *allObjects = [fetchedResultsController fetchedObjects];

    NSSortDescriptor *sortNameDescriptor = 
                       [[[NSSortDescriptor alloc] initWithKey:@"name" 
                                 ascending:ascending] autorelease];

    NSArray *sortDescriptors = [[[NSArray alloc] 
                     initWithObjects:sortNameDescriptor, nil] autorelease];

    // items is a synthesized ivar that we use as the table view
    // data source.
    [self setItems:[allObjects sortedArrayUsingDescriptors:sortDescriptors]];

    // Tell the tableview to reload.
    [itemsTableView reloadData];    
}

So the sort descriptor I've used is called "name", but you would change this to the name of the field you want to sort by in the fetched results. Also, the items ivar I've referenced would be your new table view data source. Your table view delegates would now be something like this:

- (NSInteger)tableView:(UITableView*)tableView 
 numberOfRowsInSection:(NSInteger)section
{
    return [items count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView
         cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Get your table cell by reuse identifier as usual and then grab one of
    // your records based on the index path
    // ...

    MyManagedObject *object = [items objectAtIndex:[indexPath row]];

    // Set your cell label text or whatever you want 
    // with one of the managed object's fields.
    // ...

    return cell;
}

Not sure if this is the best way, but it should work.

Matt Long
  • 24,438
  • 4
  • 73
  • 99
  • 1
    At the risk of being a premature optimiser: Would this stop being practical after a certain number of elements? If indexed, the DB would be much more efficient at sorting. – TimCinel Jan 04 '12 at 01:28
  • This is also very useful when one needs to sort on a transient property (which NSFetchedResultsController won't do) – RunLoop Nov 19 '15 at 04:15
3

Andreas Schaefer answer worked for me. The trick is setting a new parameter for the fetch request with whether it is this code:

[[fetchedResultsController fetchRequest] setSortDescriptors:sortDescriptors];

OR

[[fetchedResultsController fetchRequest] setPredicate:predicate];

Before calling this:

if (![[self fetchedResultsController] performFetch:&error]) {
        // Handle you error here
}

[self.tableView reloadData];

it appears that when you set a new parameter, than the NSFetchedResultsController will perform a new fetchrequest based upon what you set.. Without setting a new parameter, it won't perform the re-fetch and just calling performFetch it won't work..

Hope this helps someone else..

sudo
  • 1,648
  • 1
  • 20
  • 22
1

fetchRequest is a read-only property. The line of code in your post will not work. If you want to use a different fetch request, you'll need to replace your controller with a new NSFetchedResultsController. Your table won't reload automatically. You'll need to send it a reloadData message some time after you've replaced the NSFetchedResultsController.

Alex
  • 26,829
  • 3
  • 55
  • 74
  • 10
    Although you can't create replace the fetchRequest property of the NSFetchedResultsController (it is read only), you CAN change the properties of the fetchRequest and re-fetch. This saves you from having to recreate the NSFetchedResultsController. – Corey Floyd Dec 29 '09 at 06:28
  • Is there any possibility to change the sectionNameKeyPath without creating a new NSFetchedResultsController? – ComSubVie Feb 10 '10 at 17:21
  • 1
    The `sectionNameKeyPath` is a readonly property, so I think you would need to create a new `NSFetchedResultsController`. – Alex Feb 10 '10 at 18:08