简体   繁体   English

在 Coredata 中存储自定义 Class 类型数组

[英]Storing Custom Class type array in Coredata

I am trying to store custom class type array in coredata.我正在尝试将自定义 class 类型数组存储在 coredata 中。

What I've got setup is an Entity called Node with properties value of type string and children of type Transformable .我设置的是一个名为Node的实体,其属性value string 类型, children项类型为Transformable The children property is supposed to store an array of type Node as in the code below. children属性应该存储一个Node类型的数组,如下面的代码所示。

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: .xcdatamodel设置:

在此处输入图像描述

Currently the app crashes with error message "This decoder will only decode classes that adopt NSSecureCoding. Class 'Node' does not adopt it."目前应用程序崩溃并显示错误消息“此解码器将仅解码采用 NSSecureCoding 的类。Class 'Node' 不采用它。” 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.这就是 CoreData 关系的用途。

Under your Node entity:在您的Node实体下:

  1. Add a relationship children of type "To Many" with destination Node .使用目标Node添加类型为“To Many”的关系children项。 No inverse.没有逆。
  2. Add a relationship parent of Type "To One" with destination Node , set its inverse to children添加类型为“To One”的关系parent节点与目标Node ,将其逆设置为children节点
  3. Go back to the children relationship and set its inverse to parent Go 返回children关系并将其逆设置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.我建议为children使用“Cascade”,这意味着如果你删除一个父级,它的所有子级也会被删除。 "Nullify" makes sense for parent , meaning if you delete a child it just removes the parent's connection to that one child. “无效”对parent有意义,这意味着如果您删除一个孩子,它只会删除父母与该孩子的连接。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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