Post

Replies

Boosts

Views

Activity

Reply to SwiftData ModelContext.insert crashes, why?
I would keep the ModelContainer as a stored property and create the ModelContext in each test or even better create both the container and context objects in each test. As for the issue with your initial code, the modelContext stored property is a reference to the modelContainer.mainContect but since the modelContainer object is local to the setUp method it will be released and the reference will no longer be valid when that method exits in your second solution the modelContext is a newly created object so it will remain in memory as long as the test is running.
Aug ’25
Reply to Complex Swift Data Relationships...
It looks much better but be careful with those delete rules, why do you want to delete the teacher and students if you delete a class? Both the teacher and students might be in other classes, right? I would use nullify in most cases an only use cascade if I know that was exactly what I wanted to do.
Topic: Design SubTopic: General Tags:
Jul ’25
Reply to Complex Swift Data Relationships...
Some will be easy to get like all teachers for a school but others will require a little more work. One important thing to remember is that you add relationships to define your models and how they relate and not for helping with some queries you might want to implement. That said, one further relationship to consider is between School and Student so that a student can only take classes that belongs to the school they are assigned to.
Topic: Design SubTopic: General Tags:
Jun ’25
Reply to Complex Swift Data Relationships...
You haven't told us exactly what your issue is but something I spotted with your design that I don't think is correct is the relationship between Teacher and Student. As I see it your design will be simpler and more correct if you complete remove that relationship. A teacher holds (has) one or more classes A student attends (has) one or more classes So indirectly you have the relationship between Teacher and Student via the SchoolClass model. A bit unrelated but I prefer to use the @Relationship macro with the inverted argument for one of the relationship properties since it makes the code clearer for me (and it is also helpful for SwiftData)
Topic: Design SubTopic: General Tags:
Jun ’25