How to update realm data when moving data in swift?

Viewed 72

When moving the position of the cell in the table view, the data of the realm is also updated.

I did the following as I did on Android, but it doesn't work. Can you help me?

func updateMoveData(title:String, listId:Int, id:Int, icon:Int)
{
    let realm = try! Realm()
    
    let getDbData = realm.object(ofType: MainListRealm.self, forPrimaryKey: id)

    try! realm.write {
        getDbData?.title = title
        getDbData?.listId = listId
        getDbData?.icon = icon
    }
}

func tableView(_ tableView: UITableView, moveRowAt fromIndexPath: IndexPath, to: IndexPath) {
    
    let tempstart: Int = to.row
    let tempend: Int = fromIndexPath.row
    let from: Int = to.row
    let too: Int = fromIndexPath.row
    
    if from < too {

        updateMoveData(title: mDataSet![tempend].title, listId: mDataSet![tempend].listId, id: mDataSet![tempstart].id, icon: mDataSet![tempend].icon)
        for i in from...too-1 {
            //print("i = \(i)")
            updateMoveData(title: mDataSet![i].title, listId: mDataSet![i].listId, id: mDataSet![i+1].id, icon: mDataSet![i].icon)
        }

    } else if from > too {

        updateMoveData(title: mDataSet![tempend].title, listId: mDataSet![tempend].listId, id: mDataSet![tempstart].id, icon: mDataSet![tempend].icon)
        //for i in from...too+1 {
        for i in (too+1...from).reversed() {
            //print("i = \(i)")
             updateMoveData(title: mDataSet![i].title, listId: mDataSet![i].listId, id: mDataSet![i-1].id, icon: mDataSet![i].icon)
        }
    }
    
}
0 Answers
Related