Last active
March 30, 2017 19:45
-
-
Save SixBe/19b1f733110d47fcec03f13b93a98ca0 to your computer and use it in GitHub Desktop.
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
public extension NSManagedObjectContext { | |
func addContextDidSaveNotificationObserver(center: NSNotificationCenter, handler: NSNotification -> ()) -> NSObjectProtocol { | |
return center.addObserverForName(NSManagedObjectContextDidSaveNotification, object: self, queue: nil) { notification in | |
handler(notification) | |
} | |
} | |
func performMergeChangesFromContextDidSaveNotification(notification: NSNotification) { | |
self.performBlock { | |
self.mergeChangesFromContextDidSaveNotification(notification) | |
guard let updatedObjects = notification.userInfo?[NSUpdatedObjectsKey] as? Set<NSManagedObject> else { | |
return | |
} | |
updatedObjects.map({ $0.objectID }).forEach { objectID in | |
guard let object = try? self.existingObjectWithID(objectID) else { | |
return | |
} | |
self.refreshObject(object, mergeChanges: false) | |
} | |
} | |
} | |
} | |
// Prototype of a CoreDataStack class to illustrate how you could use the `NSManagedObjectContext` extension methods | |
class CoreDataStack { | |
var mainContext: NSManagedObjectContext | |
var backgroundContext: NSManagedObjectContext | |
var backgroundObserver: NSObjectProtocol? | |
deinit() { | |
if let backgroundObserver = self.backgroundObserver { | |
NSNotificationCenter.defaultcenter().removeObserver(backgroundObserver) | |
} | |
} | |
init() { | |
//.... | |
// A bunch of initialization code here where you define backgroundContext and mainContext | |
//.... | |
// Somewhere else in your code you would register your main context to listen to `NSManagedObjectDidChangeNotification` | |
// coming from the background context like so | |
backgroundObserver = backgroundContext.addContextDidSaveNotificationObserver( | |
NSNotificationCenter.defaultcenter(), | |
handler: processBackgroundContextDidSaveNotification | |
) | |
} | |
private func processBackdroundContextDidSaveNotication(notification: NSNotification) { | |
mainContext.performMergeChangesFromContextDidSaveNotification(notification) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment