Search code examples
swiftrealmrealm-list

Object in Realm List is not updated


I have a model that holds a List of MyGroup.

fileprivate let groups: List<MyGroup>

MyGroup inherits from Realm's Object. It has a computed property percentage and a property oldPercentage which is used to store the last computed property. I do not want to save this to the database so I ignore it.

class MyGroup: Object {
    override static func ignoredProperties() -> [String] {
        return ["oldPercentage"]
    }

    dynamic var oldPercentage: Double = 0

    var percentage: Double {
        //does some basic calculations
    }

    dynamic var name: String = ""
}

The problem lies in the code snippet below.

do {
    let group = groups[indexPath.row]
    //group.percentage = 0.5, group.name = "Hi"
    try realm.write {
        group.oldPercentage = group.percentage
        print(group.oldPercentage) //prints 0.5
        print(groups[indexPath.row].oldPercentage) //prints 0.0

        groups[indexPath.row].oldPercentage = group.percentage
        print(groups[indexPath.row].oldPercentage) //prints 0.0

        groups[indexPath.row] = group
        print(groups[indexPath.row].oldPercentage) //prints 0.0

        group.name = "Test"
        print(groups[indexPath.row].name) //prints "Test"
    }
catch { ... }

I basically want to get the group, change the oldPercentage property and pass it back to my UICollectionView.

I am getting the group that was selected by an indexPath. This works fine and gives me the correct group. Then, I want to change the value of oldPercentage to percentage. When I do it on the local variable group, it changes its value correctly. However, the object in the groups list is not updated.

I also tried to change the group's oldPercentage value without creating a local variable. I did not expect a different behavior than the code above and there wasn't.

My last attempt was to assign the group object that successfully printed the correct oldPercentage to groups at the indexPath. It did not work either.

When working with the name property that is saved in the database, the object behaves as expected and the value is updated correctly.

What do I have to do to update my group in the List?


Solution

  • Properties ignored by Realm are specific to each object instance, and indexing a List returns a new object each time. You will need to either not ignore oldPercentage or pass the instance that you set oldPercentage on directly to the thing which needs to read it.