简体   繁体   中英

Save array values in a Realm Database

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM