0

So I'm using the NSFetchedResultsController for an entity that is always increased by 10 or any number divisible by 10. The issue I'm having is that after the delegate methods are called for the NSFetchResultsController and the rows are inserted, the tableView will scroll to some random spot (usually towards the bottom of the table). I don't know if this is an issue with the heights of the cells (dynamic), or the fact that the cells contain images that need to be loaded, or if I'm handling the delegate methods wrong, or if I'm creating the objects wrong. Any help would be appreciated

Also, I'm using MoPub hence the mp_

NSFetchedResultsControllerDelegate Methods

func controllerWillChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) {
    self.tableView.mp_beginUpdates()
}

func controller(_ controller: NSFetchedResultsController<NSFetchRequestResult>, didChange anObject: Any, at indexPath: IndexPath?, for type: NSFetchedResultsChangeType, newIndexPath: IndexPath?) {
    switch type {
    case NSFetchedResultsChangeType.insert:
        guard let insertIndexPath = newIndexPath else { return }
        self.tableView.mp_insertRows(atIndexPaths: [insertIndexPath], with: .fade)
    case NSFetchedResultsChangeType.delete:
        guard let deleteIndexPath = indexPath else { return }
        self.tableView.mp_deleteRows(atIndexPaths: [deleteIndexPath], with: .fade)
    default:
        break
    }
}

func controllerDidChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) {
    self.tableView.mp_endUpdates()
}

Inserting method

for index in 0..<posts.count {
    let post = posts[index]
    guard let _ = RecentPost.createInManagedObjectContext(context: context, post: post, sequence: index) else { continue }
}

The createInManagedObjectContext is just a method I use to insert the new object, and the post.count is always a dividend of 10

David
  • 77
  • 2
  • 10

1 Answers1

0

Since my cell heights are dynamic, I was setting the estimatedRowHeight to 300, changing it to 1000 seemed to fix my problem. If you know of any other way to fix it besides this, or any improvement to my code, let me know. Thanks

This is what lead me to my answer. https://stackoverflow.com/a/38867302/4745553

EDIT

I actually was still having an issue and since I was responding to multiple changes, I was just using the controllerDidChangeContent delegate method and called tableView.reloadData() in their. Their is no animation but that's okay with what I'm doing.

This helped me fix it as well. https://stackoverflow.com/a/3013353/4745553

Community
  • 1
  • 1
David
  • 77
  • 2
  • 10