My app is crashing when one CloudKit device deletes a model instance and another opens a view that (used to) include reference to that instance. Must I handle that case in my code? If so, how can I be notified before the rest of my code runs?
SwiftData CloudKit - Avoid Crashes on model instance deletion
When a model instance is deleted, SwiftData nullifies the instance by setting its properties to nil
. If you hold a model instance in that state and update a SwiftUI view with it, a crash may be triggered.
To avoid this kind of crash, you will need to avoid using a deleted model instance in any way. For example, if your SwiftUI view has a state (@State
) that references an optional model instance, and provides a button to delete the instance, you can set the state to nil
immediately after deleting the instance.
If your app logic doesn't know when the object is deleted, you might consider observing the relevant notifications, like .NSManagedObjectContextDidSave
, and updating the reference accordingly. I provided a code example that shows how to observe the notification in this post.
In the case of SwiftData + CloudKit, where NSManagedObjectContextDidSave
may not be triggered, consider observing .NSPersistentStoreRemoteChange
instead, as mentioned in the other post.
This discussion applies to Core Data as well, btw.