gpt4 book ai didi

swift - Realm - 将 child 添加到 parent ,然后查询 parent 的结果

转载 作者:可可西里 更新时间:2023-11-01 01:25:53 25 4
gpt4 key购买 nike

我正在研究如何将子级添加到 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)
}

我想创建一定数量的 child ,添加到关系中

然后当我尝试查询它时;

    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 {

我想获取给定 child 的所有 parent 姓名的列表;通常我会这样做:

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

但在 Realm 中,我无法访问 parent 的姓名。

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

非常感谢

最佳答案

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

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

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

关于swift - Realm - 将 child 添加到 parent ,然后查询 parent 的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41502476/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com