领域 - 将子级添加到父级,然后在父级

时间:2017-01-06 09:20:20

标签: swift realm parent-child

我正在研究如何将子项添加到Realm(Swift)父项,我想查询结果。

然而,我想要崩溃

do {
   let realm = try Realm()
   try realm.write {

       for locomotive in locomotives
       {
           realm.add(locomotive, update: true)
       }


       let locomotives = realm.objects(Locomotive.self)
       for locomotive in locomotives {
           print (locomotive.name)
           for _ in stride(from: 0, to: locomotive.qty, by: 1) {
               let engine : Engine = Engine.init()
               locomotive.engines.append(engine)
           }
       }

   }
} catch let error as NSError {
   //TODO: Handle error
   print(error.localizedDescription as Any)
}

我想创建一定数量的孩子,将其添加到关系中

然后当我尝试查询时;

    let locomotives = realm.objects(Locomotive.self)

    print(locomotives.count)

// Find all children that are linked to this specific parent
    for loco in locomotives {
        let engines = realm.objects(Engine.self).filter("parent == \(loco)")

        print("listing engines")
        for engine in engines {
            print ("engine: \(engine.parent)")
        }
    }

我的父类是(最基本的减去任何映射代码)

class Locomotive: Object, Mappable {
    dynamic var engineid: String = ""
   var engines = List<Engine>()
}

我的子类是:(最基本的减去任何映射代码)

class Engine: Object {
    let parent = LinkingObjects(fromType: Locomotive.self, property: "engines")
}

这会导致崩溃:

*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Unable to parse the format string "parent == Locomotive {

我想获得给定孩子的所有父母姓名的列表;通常我会这样做:

for each child in parent.array
{
print child.parent.name
}

但是在领域,我无法访问父母的名字。

如何对父子关系以及与上述类似的命令进行查询(获取父级的名称属性)?

非常感谢

1 个答案:

答案 0 :(得分:2)

领域LinkingObjects对象不代表单个对象;它们代表一组潜在的多个对象。因此,有必要查询您的对象是否存在于该数组中,而不是查询是否相等。

let engines = realm.objects(Engine.self).filter("%@ IN parent", loco)

此外,由于Realm查询符合NSPredicate,因此必须使用旧式%@表示法,而不是Swift的内联代码语法。