2017-04-11 30 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