【问题标题】:Loop through array and add each value to Realm database Swift 3遍历数组并将每个值添加到领域数据库 Swift 3
【发布时间】:2017-06-16 22:36:48
【问题描述】:

我的班级定义为:

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

【问题讨论】:

    标签: ios arrays swift realm


    【解决方案1】:

    您有两个数组,一个包含 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中放置循环进行批处理操作,这样可以确保写入连接一次。

    【讨论】:

    • 我了解您的大部分内容,但let locationForTag = location[index] 如何遍历所有位置?如果index 被定义为上面的0,那不是只从数组中提取第一个值吗?
    • 您在添加 += 1 之前的答案完全相同。我不知道怎么做。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多