Robert
Robert

Reputation: 35

Discrepancy between the tableView and Realm database

While implementing swipe-to-delete feature I'm facing the following problem: When I delete the item, the last item from the array occupies its place.

So for example I have the array [1,2,3,4,5]. After deletion of 2 (index 1), the array in the database looks this [1,5,3,4]. But the table view displays everything correct [1,3,4,5]. Why is it so? I want Realm items to be saved this way [1,3,4,5].

Below if the function implementation:

override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
        if editingStyle == .Delete {
            try! realm.write {
                let itemToDelete = items[indexPath.row]

                realm.delete(itemToDelete)

            }
            tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Top)
        }
    }

I'd really appreciate your help!

Upvotes: 0

Views: 62

Answers (2)

jpsim
jpsim

Reputation: 14409

Please keep in mind that Results aren't guaranteed to preserve order of insertion. For performance reasons, items may be reordered to keep the Realm file small, or to keep operations fast.

List properties are guaranteed to preserve their order of insertion.

If you want stable ordering of your Results, make sure to sort them.

This is covered in Realm's docs on sorting.

Upvotes: 3

Michael
Michael

Reputation: 9044

Since you are using realm.delete rather than myList.remove, I assume that itemToDelete is a stand-alone object rather than an instance in a Realm List. The sequence of items in a Realm List is guaranteed, but not for retrieval of objects. Therefore if you're just using realm.objects, the sequence cannot be guaranteed, unless you apply your own filter.

I assume you're using Realm Browser and expecting the sequence to match, which it won't.

Upvotes: 2

Related Questions