Search code examples
iosarraysswiftrealm

Loop through array and add each value to Realm database Swift 3


I have my class defined as:

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

I also have two arrays defined as:

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

I would like to loop through the first array and add each value to my realm Device.assetTag object and loop through my second array and add each value to the Device.location object.

I tried using the code from the Realm readme to just add data from the first array but it did not seem to loop:

let realmArray = Device(value: array)

let realm = try! Realm()


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

Solution

  • You have two arrays one that holds asetTags and Another location so first you have to build the object from those. You can do something like following (probably refactoring needed)

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

    Remember to put loop within realm.write for batch operation, this ensure the connection to write is made once.