Saving Array to Realm in Swift?

前端 未结 2 1623
无人及你
无人及你 2021-01-11 11:47

Is it possible to save an array of objects to Realm? Anytime I make a change to the array it should be saved to Realm.

My current solution is to save ob

相关标签:
2条回答
  • 2021-01-11 12:08

    Swift 3

    func saveRealmArray(_ objects: [Object]) {
            let realm = try! Realm()
            try! realm.write {
                realm.add(objects)
            }
        }
    

    And then call the function passing an array of realm 'Object's:

    saveRealmArray(myArray)
    

    Note: realm.add(objects) has the same syntax of the add function for a single object, but if you check with the autocompletion you'll see that there is: add(objects: Sequence)

    0 讨论(0)
  • 2021-01-11 12:27

    To save lists of objects you have to use a Realm List, not a Swift Array.

    let objects = List<CustomObject>()
    

    Then, you can add elements:

    objects.append(object1)
    

    Take a look at to many relationships and Collections sections of the official docs.

    0 讨论(0)
提交回复
热议问题