Search code examples
swiftuitableviewrealmcell

Deleted tableviewcell gets replaced by last cell


I've got a problem with my tableView that is filled with realm objects. When I delete a cell the last cell of the tableView is jumping into the place of the removed cell. Anybody knows what could be the reason for this behavior?

 func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
    if editingStyle == UITableViewCellEditingStyle.delete{

        self.updateModel(at: indexPath)
        self.loadTimes()
    }
}

func loadTimes(){

    results = realm.objects(Times.self)
    tableView.reloadData()
}

 func updateModel(at indexpath: IndexPath) {
    if let itemForDeletion = results?[indexpath.row] {
        do{
            try self.realm.write {
                self.realm.delete(itemForDeletion)
            }
        } catch {
            print("Error saving context \(error)")
        }
    }
}

Solution

  • Realm guarantees consistent order of Results only when query is sorted. Try adding call to sorted

    results = realm.objects(Times.self)
    

    becomes

    results = realm.objects(Times.self).sorted(byKeyPath: "time")