Search code examples
iosswiftlistrealm

Realm AddOrUpdate an object with a list of objects overrides the later


I have 2 classes:

class RealmUser: Object {
    @objc dynamic var id: String = ""
    @objc dynamic var age: Int? = nil
    @objc dynamic var name: String? = nil
}

and

class Event: Object {
    @objc dynamic var id: String = ""
    @objc dynamic var name: String = ""
    let participants = List<RealmUser>()
}

and let' say that currently in DB I have

  • User 1 / 18 years old / "Foo"
  • User 2 / 25 years old / "Bar"

Now when I receive an Event from an API which contains a minimal representation of Users such as:

{
    event_id: 10,
    name: "Super Event",
    participants: [
        {
            user_id: 1,
            name: "Foo"
        },
        {
            user_id: 2,
            name: "New Bar"
        },
    ]
}

So there is no age, Realm will override the existing Users instead of merging the data.

What I expected in DB at the end is to have the full User objects updated.

Instead, the variable age has been reset to nil as if it wasn't updated but overrided.

I'm calling the function realm.add(parsedEvents, update: true)


Solution

  • Realm cannot magically determine that when you add an object with a nil field you want it to ignore that field rather than set it to nil.

    One solution would be to instead use realm.create(parsedEvents, update: true) and pass it a Dictionary which is missing the keys that you do not want to update rather than passing it an object.