Skip to content

Instantly share code, notes, and snippets.

@nakiostudio
Last active June 25, 2019 14:04
Show Gist options
  • Save nakiostudio/76f58769461feac9fe9272dd4726f865 to your computer and use it in GitHub Desktop.
Save nakiostudio/76f58769461feac9fe9272dd4726f865 to your computer and use it in GitHub Desktop.
Make RealmSwift write and update an Object keeping the existing relationships
/**
Writes a set of objects in the database.
- parameter objects: Array of `Objects` to be stored on the database
- parameter configuration: Realm `Configuration` in which the write action will be performed
- parameter update: Enabled the custom *update* maintaining existing relationships
*/
static func write(objects : [Object], configuration: Realm.Configuration, update: Bool = false) {
if let realm = try? Realm(configuration: configuration) {
realm.beginWrite()
for object in objects {
if let key = object.dynamicType.primaryKey(), value = object[key] where update {
if let existingObject = realm.objectForPrimaryKey(object.dynamicType, key: value) {
let relationships = existingObject.objectSchema.properties.filter { $0.type == .Array }
for relationship in relationships {
if let newObjectRelationship = object[relationship.name] as? ListBase where newObjectRelationship.count == 0 {
object[relationship.name] = existingObject[relationship.name]
}
}
}
}
realm.add(object, update: update)
}
do {
try realm.commitWrite()
}
catch let writeError {
debugPrint("Unable to commit write: \(writeError)")
}
realm.refresh()
}
}
@pomarec
Copy link

pomarec commented Aug 23, 2017

Do you manage to get List properties in existingObject.objectSchema.properties ?
I have read (sorry don't remember where) that they are stored in computedProperties that is not available in swift

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment