merge changes to main context synchronously or asynchronously depending on the caller intention (fixes #65)

This commit is contained in:
John Rommel Estropia
2016-05-07 12:18:54 +08:00
parent b9a2f96d6e
commit 26ae6293ca
2 changed files with 42 additions and 3 deletions

View File

@@ -82,14 +82,28 @@ internal extension NSManagedObjectContext {
object: rootContext,
closure: { [weak context] (note) -> Void in
context?.performBlock { () -> Void in
guard let rootContext = note.object as? NSManagedObjectContext,
let context = context else {
return
}
let mergeChanges = { () -> Void in
let updatedObjects = (note.userInfo?[NSUpdatedObjectsKey] as? Set<NSManagedObject>) ?? []
for object in updatedObjects {
context?.objectWithID(object.objectID).willAccessValueForKey(nil)
context.objectWithID(object.objectID).willAccessValueForKey(nil)
}
context?.mergeChangesFromContextDidSaveNotification(note)
context.mergeChangesFromContextDidSaveNotification(note)
}
if rootContext.isSavingSynchronously == true {
context.performBlockAndWait(mergeChanges)
}
else {
context.performBlock(mergeChanges)
}
}
)

View File

@@ -55,6 +55,26 @@ internal extension NSManagedObjectContext {
}
}
internal var isSavingSynchronously: Bool? {
get {
let value: NSNumber? = getAssociatedObjectForKey(
&PropertyKeys.isSavingSynchronously,
inObject: self
)
return value?.boolValue
}
set {
setAssociatedWeakObject(
newValue.flatMap { NSNumber(bool: $0) },
forKey: &PropertyKeys.isSavingSynchronously,
inObject: self
)
}
}
internal func isRunningInAllowedQueue() -> Bool {
guard let parentTransaction = self.parentTransaction else {
@@ -89,7 +109,9 @@ internal extension NSManagedObjectContext {
do {
self.isSavingSynchronously = true
try self.save()
self.isSavingSynchronously = nil
}
catch {
@@ -137,7 +159,9 @@ internal extension NSManagedObjectContext {
do {
self.isSavingSynchronously = false
try self.save()
self.isSavingSynchronously = nil
}
catch {
@@ -185,5 +209,6 @@ internal extension NSManagedObjectContext {
private struct PropertyKeys {
static var parentTransaction: Void?
static var isSavingSynchronously: Void?
}
}