I have a UITableView
populated by NSFetchedResultsController
. The original sample works fine. I can add, delete, modify, etc. With zero problems. But I want to add custom sorting to the table. I do this by modifying the NSFetchedResultsController
to use a different set of sortDescriptor
and a different sectionNameKeyPath
. Here is the code in which I change the selection:
-(void)changeFetchData { fetchedResultsController = nil; NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init]; NSEntityDescription *entity = [NSEntityDescription entityForName:@"Object" inManagedObjectContext:managedObjectContext]; [fetchRequest setEntity:entity]; NSString *sortKey = @"sortKey"; NSString *cacheName = @"myNewCache"; BOOL ascending = YES; NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:sortKey ascending:ascending]; NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:sortDescriptor, nil]; [fetchRequest setSortDescriptors:sortDescriptors]; NSFetchedResultsController *aFetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:managedObjectContext sectionNameKeyPath:sortKey cacheName:nil]; self.fetchedResultsController = aFetchedResultsController; fetchedResultsController.delegate = self; [aFetchedResultsController release]; [fetchRequest release]; [sortDescriptor release]; [sortDescriptors release]; NSError *error; if (![[self fetchedResultsController] performFetch:&error]) {
When I call this method, it works fine. The table immediately reorders itself to use the new section information and new sorting options. But if I add or remove elements to the data, TableView does not update its information, causing crashes. I can NSLog count the total number of objects in the fetchedResultsController file and see how it increases (and decreases), but if I NSLog for the return values ββfor numberOfRowsInSection
to track changes there, the method is called, but the values ββdon't change. Get the following crash (to add, but removing it seems to be)
Invalid update: invalid number of lines in section 2. The number of lines contained in an existing section after updating (3) must be equal to the number of lines contained in this section before updating (3), plus or minus the number of rows inserted or deleted from this section (1 inserted, 0 removed). with userInfo (null)
If I restart the application, I see the added item or cannot see the deleted item, so I am changing the data source correctly.
Any ideas?
source share