I have two models a Person
and a Possession
the Person model has a one to many
relationship to the Possession model.
meaning each possession can only have one person but a person can have multiple possessions.
I have set my model like the following
Person:
@Model
class Person {
@Attribute(.unique)
let personID: String
@Relationship(.cascade, inverse: \Possession.person)
var possetions: [Possession]?
init(id: String, possessions: [Possession]) {
self.personID = id
self.possetions = possessions
}
}
Possession:
@Model
class Possession {
@Attribute(.unique)
let id: String
let name: String?
var person: Person?
init(id: String, name: String, person: Person) {
self.id = id
self.name = name
self.person = person
}
}
If i set a breakpoint i see that all the posessions are loaded into the memory this is something i do not want to happen.
In Core Data we get a relationship fault however, i am not seeing the same behavior in SwiftData.
here's how my view is implemented
struct ContentView: View {
@Environment(\.modelContext) private var modelContext
@EnvironmentObject private var navigationStore: NavigationStore
@Query() private var people: [Person]
var body: some View {
List {
ForEach(people) { person in
NavigationLink(value: person) {
VStack {
Text(person.personID)
}
}
.swipeActions {
Button("Delete") {
modelContext.delete(person)
}
}
}
}
.toolbar(content: {
Button("Add") {
let newPErson = Person(id: UUID().uuidString, possessions: [])
modelContext.insert(newPErson)
do {
try modelContext.save()
} catch {
assertionFailure("\(error)")
}
}
})
.navigationDestination(for: Person.self) { person in
Text("hello")
}
}
}
at the launch i do not want posessions to be loaded into the memory. I want them loaded when they are being used.