Created
September 16, 2016 02:31
-
-
Save jpmcglone/c90cceea57285b48da924aa7f7c437e2 to your computer and use it in GitHub Desktop.
Realm 'sync' function (Swift 3)
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
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