¿Cómo evitar que se mueva UITableView cuando NSFetchedResultsController agrega un nuevo registro?
MiUITableView
se desplaza hacia arriba una vez que agrego un nuevo comentario a CoreData. NSFetchedResultsController lo sabe, coloca este comentario en la parte inferior de la tabla y desplaza la tabla hacia arriba. ¿Es normal?
Mi ejemplo:
Justo antes de agregar un comentario:
Justo después de agregar un comentario (comportamiento no esperado):
Debería ser así (después de deslizarlo a mano manualmente):
Esto puede estar relacionado con la siguiente situación:
Este es un descriptor de miNSFetchedResultsController
:
NSSortDescriptor(key: "createdAt", ascending: false) //from the latest to the oldest
Pero necesito mostrar mis comentarios para rutas de índice invertidas (los últimos están al final) En otras palabras, en todas partes cuando necesito usarindexPath
Yo suelo:
private func reversedIndexPathForIndexPath(indexPath: NSIndexPath) -> NSIndexPath {
return NSIndexPath(forRow: fetchedResultsController.fetchedObjects!.count - indexPath.row - 1, inSection: 0)
}
NSFetchedResultsControllerDelegate
:
//MARK: - NSFetchedResultsControllerDelegate
func controllerWillChangeContent(controller: NSFetchedResultsController) {
self.tableView.beginUpdates()
}
func controller(controller: NSFetchedResultsController, didChangeObject anObject: AnyObject, atIndexPath indexPath: NSIndexPath?, forChangeType type: NSFetchedResultsChangeType, newIndexPath: NSIndexPath?) {
switch type {
case .Insert:
if let newIndexPath = newIndexPath {
tableView.insertRowsAtIndexPaths([reversedIndexPathForIndexPath(newIndexPath)], withRowAnimation: .Fade)
}
case .Delete:
if let indexPath = indexPath {
tableView.deleteRowsAtIndexPaths([reversedIndexPathForIndexPath(indexPath)], withRowAnimation: .Fade)
}
case .Update:
if let indexPath = indexPath {
tableView.reloadRowsAtIndexPaths([reversedIndexPathForIndexPath(indexPath)], withRowAnimation: .Fade)
}
case .Move:
if let indexPath = indexPath, let newIndexPath = newIndexPath {
tableView.deleteRowsAtIndexPaths([reversedIndexPathForIndexPath(indexPath)], withRowAnimation: .Fade)
tableView.insertRowsAtIndexPaths([reversedIndexPathForIndexPath(newIndexPath)], withRowAnimation: .Fade)
}
}
}
func controllerDidChangeContent(controller: NSFetchedResultsController) {
tableView.endUpdates()
}
¿Está relacionado con mi problema?