I’m developing an app using SwiftData. In my app, I have two models: User and Address. A user can have multiple addresses. I’m trying to use SwiftData History tracking to implement some logic when addresses are deleted. Specifically, I need to determine which user the address belonged to. From the documentation, I understand that you can preserve attributes from deleted models in a tombstone object using @Attribute(.preserveValueOnDeletion). However, this isn’t working when I try to apply this to a relationship value. Below is a simplified example of my attempts so far. I suspect that simply adding @Attribute(.preserveValueOnDeletion) to a relationship isn’t feasible. If that’s indeed the case, what would be the recommended approach to identify the user associated with an address after it has been deleted? Thank you.
@Model class User {
var name: String
@Relationship(deleteRule: .cascade, inverse: \Address.user) var addresses: [Address] = []
init(name: String) {
self.name = name
}
}
@Model class Address {
var adress1: String
var address2: String
var city: String
var zip: String
@Attribute(.preserveValueOnDeletion)
var user: User?
init(adress1: String, address2: String, city: String, zip: String) {
self.adress1 = adress1
self.address2 = address2
self.city = city
self.zip = zip
self.user = user
}
}
for transaction in transactions {
for change in transaction.changes {
switch change {
case .delete(let deleted):
if let deleted = deleted as? any HistoryDelete<Address> {
if let user = deleted.tombstone[\.user] {
//this is never executed
}
}
default:
break
}
}
}