循环遍历数组并将每个值添加到Realm数据库Swift 3

时间:2017-06-16 22:36:49

标签: ios arrays swift realm

我的课程定义为:

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对象。

我尝试使用Realm自述文件中的代码来添加第一个数组中的数据,但它似乎没有循环:

let realmArray = Device(value: array)

let realm = try! Realm()


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

1 个答案:

答案 0 :(得分: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中进行批处理操作,这样可确保连接写入一次。