2017-06-16 38 views
1

我有類定義爲:遍歷陣列,並且每個值添加到域數據庫夫特3

class Device: Object { 
     dynamic public var assetTag = "" 
     dynamic var location = "" 
    } 

我還兩個數組定義爲:

let array = ["12", "42", "52", "876"] 
let array2 = ["SC", "EDS", "DS", "EF"] 

我想循環通過第一個數組,並將每個值添加到我的領域Device.assetTag對象,並通過我的第二個數組循環,並將每個值添加到Device.location對象。

我試圖使用從境界自述文件中的代碼,剛剛從第一個數組中添加數據,但它似乎沒有循環:

let realmArray = Device(value: array) 

let realm = try! Realm() 


     try! realm.write { 
      realm.add(realmArray) 
     } 

回答

2

你有兩個數組一個所以先持有asetTags和另一個位置,您必須從這些構建對象。你可以這樣做以下(可能需要重構)

class Device: Object { 
    dynamic public var assetTag = "" 
    dynamic var location = "" 
} 

class Test { 

    let assetTags = ["12", "42", "52", "876"] 
    let locations = ["SC", "EDS", "DS", "EF"] 


    func saveDevice() { 
     let realm = try! Realm() 
     try! realm.write { 
     let allDevices = getDeviceArray() 
     for device in allDevices { 
      realm.add(device) 
     } 
    } 
    } 

func getDeviceArray() -> [Device] { 
    let requiredDevices = [Device]() 
    var index = 0 
    for tag in assetTags { 
     let locationForTag = locations[index] 
     let device = Device() 
     device.assetTag = tag 
     device.location = locationForTag 
     requiredDevices.append(device) 
     index += 1 
    } 
    return requiredDevices 
    } 

} 

記得把循環realm.write內進行批量操作,這保證寫只進行一次的連接。

+0

我明白你所說的大部分內容,但'let locationForTag = location [index]'如何循環遍歷所有的位置?如果'index'被定義爲0,那麼只會從數組中拉出第一個值? – Martheli

+0

抱歉。更新了答案 – kathayatnk

+0

你的答案在添加+ = 1之前工作完全一樣。我不知道如何。 – Martheli

相關問題