views:

426

answers:

3

Hey there,

I'm working on an app that relies on a set of data that can be sorted in a variety of ways. I've got core-data setup. I have a fetch request that brings in all of the records. I've got a sort button on the left side of the nav controller. It brings up a modal view with table that has my sort options. when you change the option it closes the modal view. I can access the selected option using [[NSUserDefaults standardUserDefaults] objectForKey:@"sortOption"].

Now I need to somehow update the fetch request with a new array of sort descriptors and change the sectionNameKeyPath.

I've tried setting fetchedResultsController to nil and calling reloadData on the table view. Nothing seems to update.

Any ideas?

Howie

+1  A: 

You should be able to simply change the properties of the NSFetchRequest object that you initiallized your NSFetchedResultsController with, then execute [resultsController performFetch:...]. For example, you can change the predicate and sort descriptors array in the NSFetchRequest then call performFetch.

See Apple's CoreDataBooks sample code if you need an example of how to use NSFetchedResultsController.

Update

Eh, unfortunately if you want to change the section key then I think you'll have to create a new NSFetchedResultsController object with the new section key. All the properties of NSFetchedResultsController seem to be readonly :(

Nimrod
seems like i can updated the fetched results, but the table isn't updating. I've tried using [self.myTable reloadData], but that just removes all the rows and shows no results.All I want to do i be able to change the sorting on the fly. How can this be so hard?
Ward
+1  A: 

Solved my problem!

Looks like all I needed to do after redefining the fetch request, is perform the fetch and reload the table data.

NSError *error = nil;

if (![[self fetchedResultsController] performFetch:&error])
{
  NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
  abort();
}
[self.tableView reloadData];
Ward
Well, I did mention calling performFetch and you were already doing reloadData...
Nimrod
you did. I'm just a moron and very new at this. - thanks for the tips.
Ward
A: 

I would make sure to delete the fetchedResultsController cache if you have enabled caching.

[NSFetchedResultsController deleteCacheWithName:@"MyCacheName"];
Monobono