简体   繁体   中英

Storing Custom Class type array in Coredata

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:

在此处输入图像描述

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM