Modifying Realm List tries to recreate linked Objects

99 views Asked by At

I have the following (simplified) Realm Models:

final class Item: Object {
    @objc dynamic var identifier: String = ""
    @objc dynamic var programSet: ProgramSet?

    override static func primaryKey() -> String? {
        return "identifier"
    }
}

final class ProgramSet: Object {
    @objc dynamic var identifier: String = ""
    @objc dynamic var editorialCategory: EditorialCategory?

    override static func primaryKey() -> String? {
        return "identifier"
    }
}
final public class EditorialCategory: Object {
    @objc dynamic var identifier: String = ""
    override public static func primaryKey() -> String? {
        return "identifier"
    }
}

final class Playlist: Object {
    @objc dynamic var id = UUID().uuidString
    @objc dynamic var name = ""
    @objc dynamic var created = Date()

    var items = List<Item>()

    override static func primaryKey() -> String? {
        return "id"
    }
}

When the user adds an item to a playlist, I try to append the ItemModel to the Playlist.items List:

try realm.write {
    playlistToModify.items.append(item)
}

My problem is that it's possible for Items to share the same EditorialCategory, so it may already be in the database. When I add other items via the Realm.add(_:update:) method, Realm won't try to recreate the linked objects if one with the same primary key exists.

The List.append(_:) method seems to force recreating the linked objects of an ItemModel when called. The app crashes in the following line from object_accessor.hpp:

throw std::logic_error(util::format("
Attempting to create an object of type '%1' with an existing primary key value '%2'.", 
object_schema.name, ctx.print(*primary_value)));

Stacktrace:

enter image description here

The object_schema.name is "EditorialCategoryModel", which is linked in ProgramSetModel, which itself is linked from ItemModel.

Is there a way to avoid this error and append the item to the list without Realm attempting to re-create every linked object? Thanks!

0

There are 0 answers