Reputation: 2001
This should be trivial but I can't get it working.
I want to move a row in a UITableView in a NSFetchedResultsControllerDelegate.
I can easily delete rows, but inserting doesn't seem to work (NSInternalInconsistencyException).
I am trying
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let destinationindex = IndexPath(item: 0, section: 0)
tableView.deleteRows(at: [indexPath], with: .fade)
tableView.insertRows(at: [destinationindex], with: .fade)
}
I have also tried
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let delobject = fetchedResultsController?.object(at: indexPath)
fetchedResultsController?.managedObjectContext.delete(delobject!)
fetchedResultsController?.managedObjectContext.insert(delobject!)
}
Of course a simple delete works; for example swipe to delete:
override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete {
if (indexPath.row != 0) {
let delobject = fetchedResultsController?.object(at: indexPath)
fetchedResultsController?.managedObjectContext.delete(delobject!)
}
}
}
Upvotes: 0
Views: 100
Reputation: 19602
Your data model must fit the tableView
so number of items in data equals number of rows in tableView
.
A FetchedResultsController
based TableView
reflects the results of a CoreData fetch request. Inserting a row in the UITableView
means inserting a new entry in CoreData.
And that is what you want to do: Create a new entry in Core Data (Like you do already do when deleting a row).
Upvotes: 1