I am learning Swift by writing a single table app view which lists the content of a Core Data table (entity) upon start-up. Then the user can reorder the rows in the table view.
I need to be able to save the newly ordered rows such that they replace the previous database table, so when the user starts the app again, the new order is shown.
The editing (re-ordering) feature is activated by a long press and calls
func tableView(_ tableView: UITableView, moveRowAt sourceIndexPath: IndexPath, to destinationIndexPath: IndexPath) {
self.projectTableView.moveRow(at: sourceIndexPath, to: destinationIndexPath)
}
A second long press then inactivates the editing feature:
// Called when long press occurred
@objc func handleLongPress(_ gestureRecognizer: UILongPressGestureRecognizer){
if gestureRecognizer.state == .ended {
let touchPoint = gestureRecognizer.location(in: self.projectTableView)
if let indexPath = projectTableView.indexPathForRow(at: touchPoint) {
if self.projectTableView.isEditing == true {
self.projectTableView.isEditing = false
db.updateAll() //this is a stub
} else {
self.projectTableView.isEditing = true
}
}
}
}
The call to db.updateAll() in 'handleLongPress' above is just a blank, and I don't know how to update the database. Is there a way to read the content of the tableView in the new sequence into an array, then replace the table in the db? Feels a little "brute force" but can't see any other solution.
moveRowAt
is called would be better?index
attribute and fetch the data sorted byindex
. InmoveRowAt
you have to adjust the indices. Just moving the rows will never affect the Core Data stack.