【发布时间】:2017-01-09 12:06:02
【问题描述】:
我正在研究如何将子级添加到 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
}
但在领域中,我无法访问父母的姓名。
如何查询父子关系以及与上述类似的命令(获取父级的名称属性)?
非常感谢
【问题讨论】:
标签: swift realm parent-child