Saving an array to the kingdom in Swift?

Is it possible to save an array of objects before Realm ? Every time I make changes to an array, it must be saved in Realm.

My current solution is to save an object for an object with for loop . To add / modify objects, calling save() will do the job, but not when I remove the 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) } } } } 
+5
source share
2 answers

To save lists of objects, you should use Realm List , not Swift Array.

 let objects = List<CustomObject>() 

Then you can add elements:

 objects.append(object1) 

Look at the many relationships and Collections sections of white papers .

+5
source

Swift 3

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

And then call the function that passes the array of the "Object:

 saveRealmArray(myArray) 

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

+1
source

All Articles