问题
I have a UITableView
which uses 2 NSFetchedResultsControllers
. Each NSFetchedResultsController
has only one section. However, the table has 4 sections. I populate the 4th section of the table with the results of one of the NSFetchedResultsControllers
. Everything works fine so far. But if the user deletes the first cell on the first section, the NSFetchedResultsControllers
are changed. The rows in the last section of the table might be deleted. When this method is called:
- (void)controller:(NSFetchedResultsController *)controller didChangeObject:(id)anObject
atIndexPath:(NSIndexPath *)indexPath forChangeType:(NSFetchedResultsChangeType)type
newIndexPath:(NSIndexPath *)newIndexPath
{
UITableView *tableView = self.tableView;
switch(type) {
case NSFetchedResultsChangeInsert:
[tableView insertRowsAtIndexPaths:[NSArray arrayWithObject:newIndexPath] withRowAnimation:UITableViewRowAnimationFade];
break;
case NSFetchedResultsChangeDelete:
NSLog(@"section: %d, row: %d", [newIndexPath section], [newIndexPath row]);
[tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
break;
...
}
The section is always 0 because it's the section of the NSFetchedResultsControllers
. Thus, the section doesn't match the correct one on the table view.
Is there a workaround? I would basically like to change the section of a NSFetchedResultsController
to 3 instead of 0.
回答1:
I found a workaround, but it would be nice to have a prettier solution.
- (void)controller:(NSFetchedResultsController *)controller didChangeObject:(id)anObject
atIndexPath:(NSIndexPath *)indexPath forChangeType:(NSFetchedResultsChangeType)type
newIndexPath:(NSIndexPath *)newIndexPath
{
UITableView *tableView = self.tableView;
if (newIndexPath != nil && controller == self.fetchedXController) {
newIndexPath = [NSIndexPath indexPathForRow:[newIndexPath row] inSection:3];
if ([tableView cellForRowAtIndexPath:newIndexPath] == nil) {
type = NSFetchedResultsChangeInsert;
}
}
if (indexPath != nil && controller == self.fetchedDomainsController) {
indexPath = [NSIndexPath indexPathForRow:[indexPath row] inSection:3];
}
switch(type) {
case NSFetchedResultsChangeInsert:
[tableView insertRowsAtIndexPaths:[NSArray arrayWithObject:newIndexPath] withRowAnimation:UITableViewRowAnimationFade];
break;
case NSFetchedResultsChangeDelete:
[tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
break;
case NSFetchedResultsChangeUpdate:
[self configureCell:[tableView cellForRowAtIndexPath:newIndexPath] atIndexPath:newIndexPath];
break;
...
来源:https://stackoverflow.com/questions/7880294/multiple-nsfetchedresultscontroller-didchangeobject