自引用实体,用于与NSFetchedResultsController的父子关系

时间:2022-07-07 00:18:28

So I have a self referencing, one-to-many relationship, Tags:

我有一个自引用,一对多关系,标签:

Tag
- Name: String
- Order: NSNumber
- SubTags: [Tag]
- ParentTag: Tag

A tag can have many subtags and can only have a single parent

一个标记可以有许多子标记,并且只能有一个父标记

My goal is to use NSFetchedResultsController to display them in this manner in a UITableView (where each tag is a cell, I'm using spaces to show hierarchy to parent):

我的目标是使用NSFetchedResultsController在UITableView中以这种方式显示它们(其中每个标记都是单元格,我使用空格向父标记显示层次结构):

Parent Tag, order 1
 Child Tag, order 1
 Child 2 Tag order 2
Parent 2 Tag, order 2
 Child 3 Tag, order 1
 Child 4 Tag, order 2

Is this even possible? Should I be storing and calculating the order keys differently so I can flatly order by that?

这是可能吗?我是否应该以不同的方式存储和计算订单键,这样我就可以轻松地进行订单了?

I've been racking my brain over this for a few days now and any advice is welcome :o)

这几天我一直在思考这个问题,任何建议都是值得欢迎的。

1 个解决方案

#1


1  

Yes, you should. As it stands, to use an FRC, you need a single method by which to order all of the entity instances, but you can't use relationship order. You can do this by:

是的,你应该。按照目前的情况,要使用FRC,您需要一个方法来对所有实体实例进行排序,但是不能使用关系顺序。你可以这样做:

  1. When you add a child, get its parent order
  2. 当您添加一个子元素时,获取其父命令。
  3. Get the child's sibling count 3 set the child's order to 'parent.siblings'
  4. 让孩子的兄弟姐妹数为3,将孩子的顺序设置为“parents .sibling”

So you would have a hierarchy and order something like:

所以你会有一个层级和秩序

Parent 1 Tag, order 1
 Child 1 Tag, order 1.1
 Child 2 Tag, order 1.2
Parent 2 Tag, order 2
 Child 3 Tag, order 2.1
 Child 4 Tag, order 2.2
  Child 5 Tag, order 2.2.1

You can tell the depth by counting the number of dots in the order, but it's better to store the depth number on the child, or at least store that depth as a transient and calculate it by counting the parents.

您可以通过计算顺序中的点数量来判断深度,但是最好将深度数字存储在子节点上,或者至少将深度存储为暂态,并通过计算父节点来计算。

#1


1  

Yes, you should. As it stands, to use an FRC, you need a single method by which to order all of the entity instances, but you can't use relationship order. You can do this by:

是的,你应该。按照目前的情况,要使用FRC,您需要一个方法来对所有实体实例进行排序,但是不能使用关系顺序。你可以这样做:

  1. When you add a child, get its parent order
  2. 当您添加一个子元素时,获取其父命令。
  3. Get the child's sibling count 3 set the child's order to 'parent.siblings'
  4. 让孩子的兄弟姐妹数为3,将孩子的顺序设置为“parents .sibling”

So you would have a hierarchy and order something like:

所以你会有一个层级和秩序

Parent 1 Tag, order 1
 Child 1 Tag, order 1.1
 Child 2 Tag, order 1.2
Parent 2 Tag, order 2
 Child 3 Tag, order 2.1
 Child 4 Tag, order 2.2
  Child 5 Tag, order 2.2.1

You can tell the depth by counting the number of dots in the order, but it's better to store the depth number on the child, or at least store that depth as a transient and calculate it by counting the parents.

您可以通过计算顺序中的点数量来判断深度,但是最好将深度数字存储在子节点上,或者至少将深度存储为暂态,并通过计算父节点来计算。