I have a simple UITableView controller that shows CoreData. I am trying to implement - (void) tableView: (UITableView *) tableView moveRowAtIndexPath: (NSIndexPath *) fromIndexPath toIndexPath: (NSIndexPath *) toIndexPath; and there were problems with the animation. The Core Data Store is being updated, but the animation does not work.
How can I make the animation correctly reflect the changes that occur with the main data objects?
For instance:
Initial order:

After item 2 above:

or, initial order:

After moving element 1 to position 3:

Here is the relevant code:
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
NSMutableArray *things = [[fetchedResultsController fetchedObjects] mutableCopy];
NSManagedObject *thing = [fetchedResultsController objectAtIndexPath:fromIndexPath];
[things removeObject:thing];
[things insertObject:thing atIndex:[toIndexPath row]];
int i = 0;
for (NSManagedObject *mo in things)
{
[mo setValue:[NSNumber numberWithInt:i++] forKey:@"order"];
}
NSLog(@"things: %@", things);
[things release], things = nil;
[managedObjectContext save:nil];
}
and delegate:
- (void)controller:(NSFetchedResultsController *)controller didChangeObject:(id)anObject atIndexPath:(NSIndexPath *)indexPath forChangeType:(NSFetchedResultsChangeType)type newIndexPath:(NSIndexPath *)newIndexPath {
NSLog(@"didChangeObject:");
UITableView *tableView = self.tableView;
switch(type) {
case NSFetchedResultsChangeInsert:
NSLog(@"ResultsChangeInsert:");
[tableView insertRowsAtIndexPaths:[NSArray arrayWithObject:newIndexPath] withRowAnimation:UITableViewRowAnimationFade];
break;
case NSFetchedResultsChangeDelete:
[tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
break;
case NSFetchedResultsChangeMove:
[tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
[tableView insertRowsAtIndexPaths:[NSArray arrayWithObject:newIndexPath] withRowAnimation:UITableViewRowAnimationFade];
break;
}
}
source
share