hi,
in many cases when you delete the Core Data object, SwiftUI may try to execute the body
property of a view in which you reference the object as @ObservedObject
.
i recall checking the .isDeleted
property and it did not always seem to return the right value ... but something that is true about the deleted object will be that all its attributes will be zeroed out. so, all optional properties will be nil, all numeric values will be 0, a date will be back in 1970 somewhere, all relationships will be nil, and so forth.
if you have nil-coalesced all properties of the Core Data object, then everything should pretty much just work. for example:
Text(myObject.name ?? "No Name")
will not crash your app, but
Text(myObject.name!)
will certainly crash.
i usually add an extension to a Core Data object so that every property is nil-coalesced. e.g., if i have a name_
attribute defined in the Core Data model, then i add
var name: String {
get { name_ ?? "No Name" }
set { name_ = newValue }
}
as an extension to the entity, and now i can freely write myObject.name
throughout SwiftUI views and not have to continually nil-coalesce everything when i use it.
you might want to check out my "build and fail in public" ShoppingList16 app, which is where i found this problem back in iOS 13, and i have not had crashes with this strategy after finding out what was happening. there's plenty of commentary in the source code on this very point.
hope that helps,
DMG