Search code examples
ioscore-datansmanagedobjectcontext

How to refetch object existing in NSManagedContext


I created UIViewController using an NSManagedObject instance, let call it A. The A has beed fetched from mainContext.

In other part of the project some kind of process have updated NSPersistedContainer using backgroundContext. During this update A changed state.

What is the best way to update UIViewController from the first paragraph. How to refetch A to update existing NSManagedObject in mainContext?


Solution

  • The right way to handle merging changes made on one context into another context is:

    1. Add an observer for the NSManagedObjectContextDidSave notification.
    2. When this notification is posted, use mergeChanges(fromContextDidSave notification: Notification) to update your context from changes made in the save operation. You can just pass the Notification along and the merge will happen, and your object will be refreshed.

    An alternative is to use refresh(_ object: NSManagedObject, mergeChanges flag: Bool) for your object. Pass true for the second argument to merge in changes from the persistent store. This is probably not as good because it only affects a single object instead of everything in the context, but it's useful in some cases.