My app uses CoreData to locally cache data from other services (3rd party, CloudKit). To simplify the logic of when I send changes from the app back to the service I use a notification listening for `NSManagedObjectContextDidSave`.
```
NotificationCenter.default.addObserver(forName: .NSManagedObjectContextDidSave, object: nil, queue: nil) { [weak self] notification in
guard
let welf = self,
let userInfo = notification.userInfo,
let context = notification.object as? NSManagedObjectContext,
context.parent == nil
else { return }
if let shouldSync = context.userInfo["ShouldSync"] as? Bool, !shouldSync {
return
}
let syncContext = welf.coreDataStack.newPrivateContext()
syncContext.name = "SyncContext"
syncContext.perform {
syncContext.userInfo["ShouldSync"] = false
let inserted = welf.objectsForKey(NSInsertedObjectsKey, dictionary: userInfo as NSDictionary, context: syncContext)
let updated = welf.objectsForKey(NSUpdatedObjectsKey, dictionary: userInfo as NSDictionary, context: syncContext)
let deleted = welf.objectsForKey(NSDeletedObjectsKey, dictionary: userInfo as NSDictionary, context: syncContext)
welf.syncManager.store(inserted, updated: updated, deleted: deleted, context: syncContext)
}
}
```
I use `ShouldSync` user info to easily ignore trying to save the changes made by `syncManager.store` which flip flags on objects to mark them as up to date or not.
```
public func newPrivateContext() -> NSManagedObjectContext {
let newPrivateContext = NSManagedObjectContext(concurrencyType: .privateQueueConcurrencyType)
newPrivateContext.persistentStoreCoordinator = storeContainer.persistentStoreCoordinator
newPrivateContext.name = "New private context"
newPrivateContext.mergePolicy = NSMergePolicy(merge: .mergeByPropertyObjectTrumpMergePolicyType)
return newPrivateContext
}
```
This is the new context I create, simply so I can add the `ShouldSync` user info without changing the context I use throughout the app and UI.
Anyways, I'm seeing some weird behavior where I flip the sync flag `object.hasSynced = false` to start syncing and when I check the `userInfo` and the contexts `registeredObjects` in `NSManagedObjectContextDidSave` notification block I see `hasSynced = true`.
How can I debug / fix this? The only method that sets `hasSynced` to true is creating the objects from the server, and within `syncManager.store(...)` so I don't think this is a problem of setting it to false and then back to true.