Changing the sortDescriptor of a FetchedResultsController dynamically. Ideas?
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? 开发者_如何学CMy 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];
}
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.
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.
精彩评论