Search code examples
iosswiftxcodeuiviewcontrolleruikit

Xcode: Swift - How to save drag and drop tableview cell positions (core data)?


Im quite new to swift development. I need some help with saving the positions of the cells after drag and drop the cells. The thing is I can drag and drop the cells without any problem. However, the cells resets to the old position when I navigate to other view controllers or when I close and open back the simulator.

I followed the another stackoverflow answers to do this but I can't find any answer relevant to my question.I have posted the codes I used to do drag and drop function. Would appreciate the help, thanks.

var notes = [Notes]()
var managedObjectContext: NSManagedObjectContext!

@IBOutlet weak var tableview: UITableView!


override func viewDidLoad() {
    super.viewDidLoad()
    
    managedObjectContext = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
    
    tableview.dragDelegate = self
    tableview.dropDelegate = self
    tableview.dragInteractionEnabled = true
}

override func viewWillAppear(_ animated: Bool) {
    self.tableview.reloadData()
    loadData()
}

func tableView(_ tableView: UITableView, itemsForBeginning session: UIDragSession, at indexPath: IndexPath) -> [UIDragItem] {
    let dragItem = UIDragItem(itemProvider: NSItemProvider())
    dragItem.localObject = notes[indexPath.row]
    return [ dragItem ]
}

func tableView(_ tableView: UITableView, performDropWith coordinator: UITableViewDropCoordinator) {
    
}


 func tableView(_ tableView: UITableView, moveRowAt sourceIndexPath: IndexPath, to destinationIndexPath: IndexPath) {
    let mover = notes.remove(at: sourceIndexPath.row)
    notes.insert(mover, at: destinationIndexPath.row)
    
    
    tableview.reloadData()

}

Update 1 : I tried this but it did not work

 func tableView(_ tableView: UITableView, moveRowAt sourceIndexPath: 
 IndexPath, to destinationIndexPath: IndexPath) {
    let mover = notes.remove(at: sourceIndexPath.row)
    notes.insert(mover, at: destinationIndexPath.row)

    do{
                try notes.managedObjectContext.save()
            } catch {
                print("Rows could not be saved")
            }




    
 

Solution

  • I saw there is a loadData() method, but can't see what it actual does.

    I guess if the loadData() method load your data from Core Data and store to the notes array? If so, then it should be the problem. Since you modified the notes(by calling notes.remove() and notes.insert()), but you has not save notes to Core Data, so after loadData() in viewVillAppear be called, you load the origin data from Core Data to notes again.

    To fix it, you should save notes to Core Data just after notes.insert().