skip to content

Your Core Data app shares its store with a widget; why does the app's list miss changes the widget saved, and how do you fix it?

level: seniorimportance: should knowfreq 40%

answer

  1. another process, another coordinator
  2. automatic merging sees only your coordinator
  3. NSPersistentHistoryTrackingKey on both sides
  4. the remote change notification is only a signal
  5. fetch history after the saved token

basics

~20 s

The widget saves through its own coordinator in another process, so no save notification reaches the app's contexts. Turn on persistent history and remote change notifications in both processes, then on each remote change fetch history after your saved token and merge it.

solid answer

~40 s

`automaticallyMergesChangesFromParent` merges saves made through the context's own coordinator or parent; the widget writes the same SQLite file through a coordinator in another process, so the app's `viewContext` keeps showing what it already loaded. Set `NSPersistentHistoryTrackingKey` and `NSPersistentStoreRemoteChangeNotificationPostOptionKey` to `true` on the store description in the app and the widget alike. Observe `.NSPersistentStoreRemoteChange`, and check again when the app returns to the foreground. On a background context, run `NSPersistentHistoryChangeRequest.fetchHistory(after:)` with the last token you saved, keep the transactions you care about (the widget sets `transactionAuthor` so they're easy to pick out), and merge their object IDs into the view context with `NSManagedObjectContext.mergeChanges(fromRemoteContextSave:into:)`. Save the newest token, and purge history once both processes have read it.

code

swift · 30 lines
swift
import CoreData

final class WidgetChangeMerger {
    private let viewContext: NSManagedObjectContext
    private let historyContext: NSManagedObjectContext
    private var lastToken: NSPersistentHistoryToken?  // used only on historyContext's queue; archive it to disk
    init(container: NSPersistentContainer) {
        viewContext = container.viewContext
        historyContext = container.newBackgroundContext()
    }
    // Call on .NSPersistentStoreRemoteChange and when the app returns to the foreground.
    func mergeWidgetTransactions() {
        historyContext.perform { [self] in
            let request = NSPersistentHistoryChangeRequest.fetchHistory(after: lastToken)
            guard let result = try? historyContext.execute(request) as? NSPersistentHistoryResult,
                  let transactions = result.result as? [NSPersistentHistoryTransaction],
                  let newest = transactions.last else { return }
            var ids: [String: [NSManagedObjectID]] = [:]
            for change in transactions.filter({ $0.author == "widget" }).flatMap({ $0.changes ?? [] }) {
                let key = change.changeType == .insert ? NSInsertedObjectsKey
                    : change.changeType == .update ? NSUpdatedObjectsKey : NSDeletedObjectsKey
                ids[key, default: []].append(change.changedObjectID)
            }
            lastToken = newest.token
            viewContext.perform { [viewContext] in
                NSManagedObjectContext.mergeChanges(fromRemoteContextSave: ids, into: [viewContext])
            }
        }
    }
}

go deeper

for a junior

Recall that the widget is another process, so the app's contexts don't hear its saves, and that persistent history is the Core Data feature that records them.

for a middle

Name both description options, what the remote change notification carries, and the fetch-after-token request that returns NSPersistentHistoryTransaction values.

for a senior

Diagnose the stale list, build the observe, fetch, filter, merge and save-token loop on a background context, and catch the read-only store a missing history key causes.

for a principal

Own the history lifecycle across processes: who authors which transactions, where tokens live, and a purge rule that never deletes history a reader still needs.

## Why the list is stale The app and its widget each run their own Core Data stack over one SQLite file in the app group. When the widget saves, its coordinator writes the file, but the app's contexts hear nothing. `automaticallyMergesChangesFromParent` merges changes saved to the context's **own** coordinator or parent context, and context-did-save notifications are posted inside one process. Objects the app's `viewContext` already loaded keep their old values, and lists built from earlier fetches keep their old rows. Refetching doesn't cure it either: Apple documents that a fetch hands back objects the context has already realised with their current in-memory state. | Mechanism | Reaches the app when the widget saves? | |---|---| | `automaticallyMergesChangesFromParent` | No, it covers the app's own coordinator and parents | | `NSManagedObjectContextDidSave` notification | No, it is posted in the saving process | | `.NSPersistentStoreRemoteChange` notification | Yes, as a signal that the store changed | | Persistent history (`NSPersistentHistoryTransaction`) | Yes, it records what changed | ## Turning history on Persistent history tracking (iOS 11) is **off by default**. Remote change notifications (the option key arrived in iOS 13) have to be switched on as well. Both are options on `NSPersistentStoreDescription`: ```swift import CoreData // Called by the app and by the widget before loadPersistentStores. func configureSharedStore(_ description: NSPersistentStoreDescription) { description.setOption(true as NSNumber, forKey: NSPersistentHistoryTrackingKey) description.setOption(true as NSNumber, forKey: NSPersistentStoreRemoteChangeNotificationPostOptionKey) } ``` - Call it from the shared stack code so the app and the widget open the store identically. - A store that has been opened with history tracking must keep being opened with it. Opened without the key, the store loads without an error but read-only, and the next save fails with a permission error (Cocoa error 513). A widget built from a stale copy of the setup code shows exactly this. - With the option on, Core Data posts `NSPersistentStoreRemoteChange` for every write to the store, including writes from other processes. Its object is the coordinator, and its user info holds the store UUID, the store URL and, when history is on, the history token of that transaction. It carries no objects. ## Consuming history 1. **Observe** `.NSPersistentStoreRemoteChange` on the app's coordinator, and also check when the app returns to the foreground, because writes made while the app wasn't running produced no notification it could observe. 2. **Fetch** on a background context: `NSPersistentHistoryChangeRequest.fetchHistory(after: lastToken)`, executed with `execute(_:)`, gives an `NSPersistentHistoryResult` whose `result` is an array of `NSPersistentHistoryTransaction`. Apple's article asks for a background context so the fetch doesn't block the main thread. 3. **Filter.** Each transaction records its `author`, `contextName`, `bundleID` and `processID`, and each `NSPersistentHistoryChange` its `changeType` and `changedObjectID`. Setting `transactionAuthor = "widget"` on the widget's context before it saves makes its transactions easy to select; filtering by entity keeps only what is on screen. 4. **Merge** into the view context on its queue. The class method `NSManagedObjectContext.mergeChanges(fromRemoteContextSave:into:)` is the one built for changes from other processes; it takes inserted, updated and deleted object IDs under `NSInsertedObjectsKey`, `NSUpdatedObjectsKey` and `NSDeletedObjectsKey`. 5. **Remember the newest token.** `NSPersistentHistoryToken` supports secure coding, so archive it with `NSKeyedArchiver` and reload it at launch. 6. **Purge.** History takes disk space, and Apple's guidance is to choose a clean-up strategy yourself. Once every reader has passed a point, delete with `NSPersistentHistoryChangeRequest.deleteHistory(before:)`. Fetching after a purged token throws an expired-token error, which a reader that fell behind must handle by reloading its data. ## Mistakes that keep the list stale - Observing the notification with a `nil` object: it then fires for every coordinator in the process that has the option on, such as a second stack the app keeps. Pass the app's coordinator as the object, and expect it to fire for the app's own saves too. - Leaving `transactionAuthor` set after a save. Apple's article resets it to `nil` after each save so later transactions aren't attributed to the wrong caller. - Not persisting the token, so every launch re-reads and re-merges all history. - Merging on the wrong queue: the merge into `viewContext` belongs inside its `perform`. - Purging history at a date the widget hasn't reached yet, so the widget's next fetch fails with an expired token. ## With more than one store A history request goes to every store on the coordinator. If the container also loads a store without history, such as a read-only catalogue, Core Data logs "History Change Request failed as no history tracking option detected on store" for it. Set the request's `affectedStores` to the shared store. ## Newer API iOS 27 adds `NSPersistentStoreCoordinator.RemoteChangeMessage`, a typed asynchronous `NotificationCenter` message whose `storeUUID`, `storeURL` and `historyToken` properties replace reading the user info dictionary. Apps that deploy to iOS 17 keep the `.NSPersistentStoreRemoteChange` notification name. How merged changes reach a list, and which contexts the app writes through, is the lesson on managed object contexts.

  • What happens if the widget opens the shared store without NSPersistentHistoryTrackingKey?
    Once a store has been opened with history tracking, opening it without the key still loads, but read-only, and the widget's next save fails with a permission error (Cocoa error 513). Keep the description setup in one function both targets call.
  • Why filter transactions instead of merging every one, including the app's own?
    The app's own saves already reached its contexts in-process, so merging them again is wasted work, and a busy store's history grows quickly. Select by transactionAuthor or contextName, or by entity so only changes to what is on screen are merged.
  • When is it safe to purge persistent history?
    Only after every reader, the app and the widget, has processed it. Delete with deleteHistory(before:) using the oldest token or date they have reached. A reader whose token was purged gets an expired-token error and must reload instead of resuming.
  • How does iOS 27 change observing remote changes?
    iOS 27 adds NSPersistentStoreCoordinator.RemoteChangeMessage, a typed asynchronous NotificationCenter message with storeUUID, storeURL and historyToken properties. An app deploying to iOS 17 still observes the .NSPersistentStoreRemoteChange notification, whose user info carries the same three values.

Persistent history is a logbook kept beside the store. Every write adds an entry; the remote change notification is a doorbell saying new entries exist, not the entries themselves; and the saved token is your bookmark, so you read only the entries after it.

  • automaticallyMergesChangesFromParent picks up saves made by the widget process.
  • The remote change notification carries the changed objects, ready to merge.
  • History tracking only needs enabling in the process that reads the history.
  • Core Data purges persistent history automatically once it has been read.
  • Refetching the list is enough, because a fetch refreshes objects already in memory.

Assumes the iOS 17 baseline, where history (iOS 11) and the remote change option (iOS 13) exist; iOS 27 adds the typed NSPersistentStoreCoordinator.RemoteChangeMessage.