Storing Custom Class type array in Coredata

262 views Asked by At

I am trying to store custom class type array in coredata.

What I've got setup is an Entity called Node with properties value of type string and children of type Transformable. The children property is supposed to store an array of type Node as in the code below.

public class Node: NSManagedObject {

    @nonobjc public class func fetchRequest() -> NSFetchRequest<Node> {
        return NSFetchRequest<Node>(entityName: "Person")
    }

    @NSManaged public var children: [Node]?
    @NSManaged public var value: String?

}

.xcdatamodel setup:

enter image description here

Currently the app crashes with error message "This decoder will only decode classes that adopt NSSecureCoding. Class 'Node' does not adopt it." So I tried it with String array instead of Node array and it seems to work.

I'm guessing something extra needs to be done to store Custom array type.

1

There are 1 answers

11
Max On BEST ANSWER

It sounds like you want a recursive data structure, where each node can have many other nodes as children and another node as its parent. This is what CoreData relationships are for.

Under your Node entity:

  1. Add a relationship children of type "To Many" with destination Node. No inverse.
  2. Add a relationship parent of Type "To One" with destination Node, set its inverse to children
  3. Go back to the children relationship and set its inverse to parent
  4. Consider what the delete rules should be. I suggest "Cascade" for children, meaning if you delete a parent all of its children are deleted too. "Nullify" makes sense for parent, meaning if you delete a child it just removes the parent's connection to that one child.