Last active
June 25, 2019 14:04
-
-
Save nakiostudio/76f58769461feac9fe9272dd4726f865 to your computer and use it in GitHub Desktop.
Make RealmSwift write and update an Object keeping the existing relationships
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
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() | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Do you manage to get
List
properties inexistingObject.objectSchema.properties
?I have read (sorry don't remember where) that they are stored in
computedProperties
that is not available in swift