Saving Array to Realm in Swift?

Deadly 提交于 2019-12-10 01:59:19

问题


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 object for object with a for loop. For append/modifying objects calling save() will do the job, but not when I remove an object from it.

class CustomObject: Object {
    dynamic var name = ""
    dynamic var id = 0

    override static func primaryKey() -> String? {
    return "id"
    }
}

struct RealmDatabase {

    static var sharedInstance = RealmDatabase()

    var realm: Realm!

    let object0 = CustomObject()
    let object1 = CustomObject()

    var array = [object0, object1]

    init() {
        self.realm = try! Realm()
    }

    func save() {

        for object in self.array {
            try! self.realm.write {
                self.realm.add(object, update: true)
            }
        }
    }

}

回答1:


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.




回答2:


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)



来源:https://stackoverflow.com/questions/38327569/saving-array-to-realm-in-swift

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!