Jon*_*man 1 key-value-coding realm swift
我正在开发一个使用 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!)
}
}
Run Code Online (Sandbox Code Playgroud)
有没有办法在没有镜像的情况下迭代属性?我真的可以发誓,我在 Realm 文档(或者甚至在 Apple 的 KVC 文档中)中读到过,您可以做类似的事情for property in Song.properties或for property in Song.self.properties实现同样的事情。
除了效率更高一点之外,我想这样做的主要原因是因为在同一个地方我认为我读过这篇文章,我认为他们说迭代(或 KVC?)仅适用于字符串、整数、布尔值和日期,因此它会自动跳过作为对象的属性(因为您无法以相同的方式设置它们)。上面的代码实际上是我的代码的简化,在实际版本中,我目前正在跳过这样的对象:
let propertiesToSkip = ["title", "artist", "genre"]
for property in mirror.children where !propertiesToSkip.contains(property.label!) {
...
Run Code Online (Sandbox Code Playgroud)
我想象过这.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)
}
Run Code Online (Sandbox Code Playgroud)
RealmObject实例通过Object.objectSchema属性公开该对象的架构。
查看Realm Swift 文档中的schema属性,Realm了解有关您可以从架构属性中获取何种数据的更多信息。:)
| 归档时间: |
|
| 查看次数: |
1472 次 |
| 最近记录: |