查找来自特定类型的对象的父级

时间:2015-02-18 15:18:42

标签: ios structure

我有一个具有这些属性的Object类:

  • 名称
  • 儿童

type有三种可能性:汽车,船,自行车。 children是一个数组,用于保存该对象的子项。

所以我可以有这样的记录:

name = "Project Titan"
type = "car"


name = "Prototype 1"
type = "car"


name = "Tail light"
type = "parts"


name = "Horns"
type = "parts"


name = "Prototype 2"
type = "car"


name = "Wheel"
type = "parts"

并像这样组织

            Project Titan
                   |
          ___________________
         |                   |
         |                   |
    Prototype 1          Prototype 2
         |                   |
    __________              wheel
   |          |
   Tail     horns
   light

或换句话说

Tail LightHornsPrototype 1的孩子。 WheelPrototype 2的孩子 Prototype 12Project Titan的孩子。

现在假设我有Tail Light的对象,想要更直接地知道它的亲子车的父母,在这种情况下将是Prototype 1。没有烧伤大脑的最佳方法是什么?

好的,您可以从上到下扫描并扫描结构的所有节点的子节点,直到您在type = car的结构中找到最近的父节点,但此扫描所有结构方法似乎是一个可怕的解决方案,特别是如果结构有数百个分支...

有什么想法吗?

2 个答案:

答案 0 :(得分:1)

支持节点双向导航的最简单方法是向您的班级添加parent属性。要记住的重要一点是将其设为weak属性,以避免父项及其子项之间的引用循环。

答案 1 :(得分:0)

试试这种方式。在孩子中,您将给出新创建的模型的名称。对于第一类对象,父级将为nil,如果它具有新子级,则传递父模型的引用。

@interface Model : NSObject

@property(nonatomic,strong) NSString *name;
@property(nonatomic,strong) NSString *type;
@property(nonatomic,weak) Model *children;
@property(nonatomic,weak) Model *parent;

@end