RLMException: Cannot add an existing managed embedded object to a List

1.3k Views Asked by At
Object1: Object
    - id: String
    - title: String
    - items: [Object2]

Object2: EmbeddedObject
    - id: String
    - title: String
    - items: [Object3]

Object3: EmbeddedObject
    - id: String
    - title: String
    - color: String

Above is a sample of the schema I have, however, for some odd reason I am consistently getting this error in RealmSwift whenever I try to add Object1 to the realm.

*** Terminating app due to uncaught exception 'RLMException', reason: 'Cannot add an existing managed embedded object to a List.'
1

There are 1 best solutions below

0
On

This error can be caused by creating the embedded object outside of a realm.write operation, and then trying to add it to a list from within a write operation. Everything must be done from within the write operation.

For example, to add a new Object3 into an Object2 you would need to do it like this:

try! realm.write {
    let newItem = Object3(id: "someID", title: "Some Title", color: "Some Color")
    object1.items[indexToWrite].items.append(newItem)
}

note: Please don't force try a realm write in a real app. :)