Save array values in a Realm Database

Viewed 3142

Im using Realm DB for saving offline data in iOS. Can I save array values directly to the Realm DB without using for loop?

1 Answers

By default, you cannot do this, Realm uses Lists:

List is the container type in Realm used to define to-many relationships.

Like Swift’s Array, List is a generic type that is parameterized on the type of Object it stores.

class MyObject: Object {
    dynamic var name = "Default"
}

func listToArray() {
    let objectsArray = [MyObject(), MyObject(), MyObject(), MyObject(), MyObject()]
    var objectsRealmList = List<MyObject>()
    
    objectsRealmList = objectsArray
}

If you are thinking of something like objectsRealmList = objectsArray that would be illegal you cannot assign an array to a realm list.

Thus, as the same logic in this answer, you would need to iterate through objectsArray:

func arrayToList() {
    let objectsArray = [MyObject(), MyObject(), MyObject(), MyObject(), MyObject()]
    let objectsRealmList = List<MyObject>()

    // this one is illegal
    //objectsRealmList = objectsArray
    
    for object in objectsArray {
        objectsRealmList.append(object)
    }
    
    // storing the data...
    let realm = try! Realm()
    try! realm.write {
        realm.add(objectsRealmList)
    }
}

Usually, the list would be as a property of an Object, you should add the object itself.

Related