views:

44

answers:

2

I'm having difficulty understanding how to update my fetchedresultscontroller with a new sort. I initialize a frc the standard way in my class. But how exactly do you modify the fetchrequest with a new sortdecription? My app has a sort selector in the appSettings that the user can change on the fly. Is there a way to update the frc dynamically? The code below is what I have in the viewWillLoad callback, but it just produces a blank table. Thanks!

[self appSettingSortOrder];     
if (sortOrderChanged) {

    //Form a new fetchrequest for the FRC and reload the table.

    NSEntityDescription *entity = [NSEntityDescription entityForName:@"Aircraft" inManagedObjectContext:managedObjectContext];

    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
    [fetchRequest setEntity:entity];

    NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:currentSortOrder ascending:YES];
    NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:sortDescriptor, nil];

    [fetchRequest setSortDescriptors:sortDescriptors];

    NSError *error = nil;

    [fetchedResultsController performFetch:&error];

    [self.tableView reloadData];

    [fetchRequest release];
    [sortDescriptor release];
    [sortDescriptors release];      
}
A: 

I suspect the value of sortOrderChanged is false. The fetch is not being performed. Set a breakpoint on the if block to make sure it is entering.

falconcreek
+1  A: 

Well, the immediate problem with this code is that while you create a new fetch request you never assign it to the FRC.

It doesn't matter because you can't change an FRC's fetch request on the fly. The NSFetchedResultsController docs make this explicit.

Important: You must not modify the fetch request. For example, you must not change its predicate or the sort orderings.

To change the sort ordering of an FRC, you must create a new FRC with a new fetch request with the new ordering.

TechZen
Emphasis needed also the `NSFetchedResultsController` `fetchRequest` property is `readonly`.
falconcreek
I read that too. So it would seem that I need create a new FRC with a new sort order and assign it's delegate to the class that has the callbacks, ie self. Probably prudent to assign the current FRC to nil. Yes/no?
Hal