In Core Data, you can use a pinned query generation to make sure that your app is working from a consistent view of the data store. If you have CloudKit sync turned on, and new changes come in that invalidate relationships, your app won't see them right away as long as it's looking at a pinned query generation.
Since Swift Data doesn't yet support query generations, how do I deal with this issue in Swift Data apps?
For example, let's say I have an address book app. I open a particular contact, and then tap a control on the screen that opens a list of images for that contact. While looking at the images, CloudKit sync retrieves changes made by other devices, which have completely removed the parent contact.
How does my app know this has happened? Suppose the image browser screen needs to refer to the parent contact, or make changes to it, but the contact is no longer there because a background sync removed it.
The new SwiftData history API introduced this year should help –
You can observe the .NSPersistentStoreRemoteChange
notification, which is posted when the framework changes the store, and detect the changes by looking into the history.
See the Track model changes with SwiftData history WWDC video for more information.
Best,
——
Ziqiao Chen
Worldwide Developer Relations.