Skip to content

Instantly share code, notes, and snippets.

@SixBe
Last active March 30, 2017 19:45
Show Gist options
  • Save SixBe/19b1f733110d47fcec03f13b93a98ca0 to your computer and use it in GitHub Desktop.
Save SixBe/19b1f733110d47fcec03f13b93a98ca0 to your computer and use it in GitHub Desktop.
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