gpt4 book ai didi

swift - 遍历对象的属性(在 Realm 中,也可能不在)

转载 作者:行者123 更新时间:2023-11-28 10:14:19 25 4
gpt4 key购买 nike

我正在开发一个使用 Realm 作为数据库的项目(稍后会提到)。我刚刚发现了键值编码,我想用它来将 TSV 表转换为对象属性(使用表中的列标题作为键)。现在它看起来像这样:

    let mirror = Mirror(reflecting: newSong)
for property in mirror.children {
if let index = headers.index(of: property.label!) {
newSong.setValue(headers[index], forKey: property.label!)
} else {
propertiesWithoutHeaders.append(property.label!)
}
}

有没有办法在没有镜像的情况下迭代属性?我真的可以发誓,我在 Realm 文档(或者甚至可能在 Apple 的 KVC 文档)中读到,你可以做一些像 for property in Song.propertiesfor property in Song.self 这样的事情.properties 实现同样的目的。

除了效率更高之外,我想这样做的主要原因是因为在我读到这篇文章的同一个地方,我想他们说迭代(或 KVC?)只适用于字符串、整数, Bools 和 Dates,所以它会自动跳过对象的属性(因为你不能以相同的方式设置它们)。上面的代码实际上是我的代码的简化,在实际版本中我目前跳过了这样的对象:

let propertiesToSkip = ["title", "artist", "genre"]
for property in mirror.children where !propertiesToSkip.contains(property.label!) {
...

我是否想象过这个 .properties 东西?或者,有没有办法以这种方式迭代,自动跳过对象/类,而不必像我上面那样命名它们?

谢谢:)

最佳答案

不,你没想到。 :)

Realm 在两个地方公开包含数据库中每种类型模型的属性的模式:在父 Realm 实例中,或在 Object 本身中。

Realm 实例中:

// Get an instance of the Realm object
let realm = try! Realm()

// Get the object schema for just the Mirror class. This contains the property names
let mirrorSchema = realm.schema["Mirror"]

// Iterate through each property and print its name
for property in mirrorSchema.properties {
print(property.name)
}

Realm Object 实例通过 Object.objectSchema 属性公开该对象的架构。

查看 schema property of Realm在 Realm Swift Documentation 中获取更多关于你可以从模式属性中获取什么样的数据的信息。 :)

关于swift - 遍历对象的属性(在 Realm 中,也可能不在),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43355795/

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