2017-04-11 32 views
0

我正在使用Realm作为数据库的项目(稍后会出现)。我刚刚发现了键值编码,我想用它将TSV表转换为对象属性(使用表中的列标题作为键)。现在它看起来像这样:迭代对象的属性(在Realm中,或者可能不是)

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?)只适用于字符串, Ints,Bools和Dates,所以它会自动跳过属性是对象(因为你不能用相同的方式设置它们)。上面的代码实际上是我的代码的简化,在实际的版本,我目前正在跳过这样的对象:

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

难道我想这.properties的事情吗?或者,有没有办法以这种方式进行迭代,自动跳过对象/类而不必像上面那样命名它们?

谢谢:)

回答

1

不,你没有想象它。 :)

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) 
} 

境界Object实例暴露所述模式用于经由所述Object.objectSchema属性该对象。

请参阅Realm Swift文档中的schema property of Realm,以获取有关可以从模式属性中获取何种数据的更多信息。 :)

+0

谢谢,这似乎是它!然而,当我检查'property.type!= Object'时,我得到“Binary operator!=不能应用于'PropertyType'和'Object.Type'类型的操作数。你知道如何将这些操作符转换为可以相等的其他?还是'properties'可能不包含对象/列表? –

+0

不客气!嗯,'property.type'是一个Objective-C枚举(https://github.com/realm/realm-cocoa/blob /255b2018c19398efaa52e816ccf59ef11be24cbd/Realm/RLMConstants.h#L51),指出该属性的实际类型。你需要确保你比较了枚举值而不是实际的类名。 – TiM