ViewContext not receiving updates from newBackgroundContext()

There is a use case in my application where I have to observe the database changes to perform some operation. To receive updates I subscribed to NSManagedObjectContextObjectsDidChangenotification (for ViewContext) and also I turned on automaticallyMergesChangesFromParent.


But, if I update or delete the object on some other context (using newBackgroundContext()), I don’t receive object did change notification but it’s working perfectly for inserting new objects.


Can you someone please guide me why it does work only for insert, not for update and delete even after enabling automaticallyMergesChangesFromParent? if it's the actual behavior, Is there any other way to solve my use case?


The documentation (in NSManagedObjectContext.h) for .automaticallyMergesChangesFromParent says:

Whether the context automatically merges changes saved to its coordinator or parent context. Setting this property to YES when the context is pinned to a non-current query generation is not supported.



What I tried

  • I debugged by testing if updated/deleted objects are already registered in the view context. Yes, those are already registered.
  • I tested the same thing using NSFetchResultController it’s working good but unfortunately, I can’t use NSFetchResultController as I use a custom view to represent the data
  • Also, I tried creating a new privateQueueConcurrencyType context and setting viewContext as a parent and it surprisingly started working so the issue is only while using newBackgroundContext() but as per document it should work properly as both are using same NSPersistentStoreCoordinator


Thanks in advance!

Replies

I'm surprised this hasn't been answered, I've observed the same thing where the context save notification is only called for the background context but not the viewContext. My FetchedResultsControllers are deleting objects because of this and require a re-fetch after controllerDidChangeContent has been called to force an update.

I'm surprised this hasn't been answered, I've observed the same thing where the context save notification is only called for the background context but not the viewContext. My FetchedResultsControllers are deleting objects because of this and require a re-fetch after controllerDidChangeContent has been called to force an update.

I have discovered that this was caused by a bug with NSPredicate where "how" the type is passed in apparently matters (even though the predicate results in the same output). My Int64 value had to be wrapped as a NSNumber in order to properly work with NSFetchedResultsController.