Reputation: 4970
I am trying to move my Core Data object graph to Realm.
Currently I have an Entity called DBNode, which has
@NSManaged var children: NSSet
@NSManaged var parentNode: DBNode
where I can store the parent node and all the children of the node.
When I have a Realm object called RLMNode: RLMObject with
dynamic var children = RLMArray(objectClassName: RLMNode.className())
dynamic var parent = RLMNode()
it crashes when first trying to add an object.
Can I do this hierarchical structure in Realm?
Edit:
It seems I can do this, and just have one node in the array:
dynamic var parent = RLMArray(objectClassName:RLMNode.className())
Would this be the recommended way? Is it as quick as the object graph in Core Data?
Upvotes: 0
Views: 2095
Reputation: 755
The reason for the crash is probably that initialisation becomes recursive, when you create a node it creates a node for its parent, which in turn needs a node etc. You can check the stack trace to see if that is the case.
Realm in Swift supports optional object properties, and they are set to nil by default, so you can do something like this:
class DBNode: RLMObject {
dynamic var name = ""
dynamic var parent: DBNode?
dynamic var children = RLMArray(objectClassName: DBNode.className())
}
Arrays can in fact not be nil, and they do have to be initialised, but they can be empty.
Beware that you might get an exception thrown if you add both an object and its parent (or children) to the Realm explicitly.s They will be added automatically since you cannot link to objects that are not persisted.
Upvotes: 2