Skip to content

Instantly share code, notes, and snippets.

@jpmcglone
Created September 16, 2016 02:31
Show Gist options
  • Save jpmcglone/c90cceea57285b48da924aa7f7c437e2 to your computer and use it in GitHub Desktop.
Save jpmcglone/c90cceea57285b48da924aa7f7c437e2 to your computer and use it in GitHub Desktop.
Realm 'sync' function (Swift 3)
import RealmSwift
extension Realm {
func sync<T: Object>(_ obj: T) {
var beganWriteTransaction = false
if !isInWriteTransaction {
beganWriteTransaction = true
beginWrite()
}
if let primaryKeyName = obj.objectSchema.primaryKeyProperty?.name,
let oldObject = object(ofType: type(of: obj), forPrimaryKey: obj.value(forKey: primaryKeyName)) {
for property in obj.objectSchema.properties {
if property != obj.objectSchema.primaryKeyProperty {
obj[property.name] = obj[property.name] ?? oldObject[property.name]
}
}
obj.willFinishSync(oldObject)
}
add(obj, update: true)
if beganWriteTransaction {
try! commitWrite()
}
}
}
extension Object {
func sync(_ realm: Realm = try! Realm()) {
realm.sync(self)
}
func willFinishSync(_ oldObject: Object) {
// Overwrite
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment