In Core Data, how do you model a Course with many Lessons and Students taking many Courses, and why give each relationship an inverse?
answer
- one relationship per direction
- maxCount 1 versus a to-many
- the context updates the other side
- the model compiler warns about a missing inverse
- no join entity until the link carries data
basics
~20 sGive Lesson a to-one course and Course a to-many lessons, set each as the other's inverse, and pair Student.courses with Course.students for many-to-many. With inverses set, Core Data updates the other side whenever you change one.
solid answer
~40 sIn Core Data a relationship is one direction of a link, described by an `NSRelationshipDescription`: a `maxCount` of 1 makes it to-one, and a to-many relationship uses 0 for no limit. So `Lesson.course` and `Course.lessons` are two relationships, and setting `inverseRelationship` on both tells the context they are one link. Then `lesson.course = course` also puts the lesson into `course.lessons`, and a delete rule can clear the other side. Many-to-many is two to-many relationships that are each other's inverse, `Student.courses` and `Course.students`; Core Data stores the links itself, so you model no join entity. You add one, such as an Enrollment, only when the link carries data like a grade. When an inverse is missing, the model compiler warns, for example `Teacher.office should have an inverse`.
code
swift · 10 linesimport CoreData
func addLesson(titled title: String, to course: Course, in context: NSManagedObjectContext) {
let lesson = Lesson(context: context)
lesson.title = title
lesson.course = course // set one side only
// Core Data has already updated the inverse side.
assert(course.lessons?.contains(lesson) == true)
}go deeper
Know how to add a to-one and a to-many relationship in the model editor, pick the inverse from the pop-up, and that a to-many property is an NSSet unless it is ordered.
Explain that the context maintains the inverse as soon as one side changes, why Nullify needs an inverse to work, and when a many-to-many needs a join entity instead.
Treat a missing-inverse warning as a review blocker, and be ready to explain how a dangling reference later shows up as an inaccessible fault that reads as a deleted object.
Set a model-review rule that every relationship has an inverse unless a written reason says otherwise, so graph integrity never depends on hand-written bookkeeping.
## What a relationship is in Core Data A **relationship** is a property of an entity whose value is other managed objects instead of a string or a number. In the model editor you add it under an entity's Relationships; in code it is an `NSRelationshipDescription`. Each one has a **destination entity**, a **cardinality** and a **delete rule**: - **To-one**: `maxCount` is 1, and the generated property is the destination class, optional, such as `var course: Course?`. - **To-many**: `maxCount` is 0 for no upper limit (or a number above 1 to cap it), and the generated property is an `NSSet?`, unordered, or an `NSOrderedSet?` when the relationship is marked ordered. - **Optional or not**: `minCount` and `maxCount` are only enforced when the relationship has a value, so an optional to-many can still be empty. A relationship points one way. `Lesson.course` lets a lesson find its course; it says nothing about how a course finds its lessons. That second direction is a separate relationship, `Course.lessons`. ## Inverses: one link, two relationships The **inverse** joins the two directions into one link. You set it in the model editor's Inverse pop-up, or with `inverseRelationship` in code. The header for `NSRelationshipDescription` puts it plainly: relationships usually come in pairs, and the reference back is called the inverse. Once the pair is declared, the managed object context maintains it for you: 1. Assigning `lesson.course = course` adds the lesson to `course.lessons` immediately, before any save. 2. Calling the generated `course.addToLessons(lesson)` sets `lesson.course` in return. 3. Moving a lesson to another course removes it from the first course's set. 4. A Nullify delete rule can clear the other side because Core Data knows which relationship that side is. | Shape | One side | Other side | |---|---|---| | One-to-many | `Lesson.course`, to-one | `Course.lessons`, to-many | | Many-to-many | `Student.courses`, to-many | `Course.students`, to-many | | One-to-one | `Teacher.office`, to-one | `Office.teacher`, to-one | ## Many-to-many without a join entity A student takes many courses and a course has many students. In Core Data that is simply two **to-many** relationships set as each other's inverse. You do not model a join entity: Core Data keeps the link records in the store itself, and the generated accessors `student.addToCourses(_:)` and `student.removeFromCourses(_:)` update both sides. Add a **join entity** only when the link has data of its own. If each student's place in a course carries an enrolment date or a grade, model an `Enrollment` entity with a to-one `student` and a to-one `course`, each with a to-many inverse (`Student.enrollments`, `Course.enrollments`). The many-to-many is then reached through the enrollments. ## What goes wrong without an inverse A relationship with no inverse is legal, and you can build a model in code without one. Compiling an `.xcdatamodel` that lacks one produces a warning such as `Teacher.office should have an inverse`, and ignoring it has real costs: - **The other side never updates.** Nothing tells the office which teacher uses it, so code that needs the reverse direction must run a fetch. - **Deletes leave dangling references.** Deleting an Office cannot clear `Teacher.office`, because there is no inverse for a delete rule to work on. The teacher's row still points at the deleted office; when you later traverse it, the context meets an inaccessible fault. With `shouldDeleteInaccessibleFaults` at its default of true, you get an object marked deleted whose attributes read as nil, not the office you expected. - **Graph integrity is now your code's job**, on every path that changes the relationship. ## Building the pair in code When the model is built in code with `NSEntityDescription`, no compiler warns you. You create both `NSRelationshipDescription` objects, set each one's `destinationEntity`, and assign each to the other's `inverseRelationship` yourself. Apple's documentation adds that a relationship description can be changed only until its model is associated with a persistent store coordinator; after that, Core Data throws. A relationship's `versionHash` includes the inverse relationship's name, so adding an inverse to a shipped model is a model change that needs a new model version. ## Generated accessors and primitive setters With codegen, a to-many relationship gets `addTo<Name>(_:)` and `removeFrom<Name>(_:)` accessors, in single-object and set forms. They, the property setter and `mutableSetValue(forKey:)` all go through Core Data's normal handling, so the inverse stays in step. `setPrimitiveValue(_:forKey:)` does not maintain it: its documentation says that when you use it on a relationship with an inverse, you are responsible for maintaining the inverse yourself. ```swift let lesson = Lesson(context: context) lesson.course = course // course.lessons already contains lesson ``` The rule of thumb: give every relationship an inverse, choose the cardinality on each side, and let the context keep both directions true.
- In Core Data, how would you record a grade for each student in each course?Replace the direct many-to-many with an `Enrollment` entity that holds the grade, a to-one `student` and a to-one `course`. Give Student and Course a to-many `enrollments` inverse each. Cascade from Student and Course to their enrollments so a deleted student takes their enrolments with them, and Nullify from Enrollment back to each side.
- In Core Data, does setPrimitiveValue(_:forKey:) on a relationship keep the inverse in step?No. Primitive accessors write the stored value directly, and Apple's documentation for `setPrimitiveValue(_:forKey:)` says that for a relationship with an inverse you must maintain the inverse yourself, whatever the cardinality. Use the property setter, the generated `addTo...` accessors or `mutableSetValue(forKey:)` and the context keeps both sides consistent.
A pair of inverse relationships is like a two-way address book entry that updates itself: write a friend's number into yours and your number appears in theirs. Leave out the inverse and you have a one-way note that the other side never hears about.
- After setting lesson.course you must also add the lesson to course.lessons yourself.
- A many-to-many relationship in Core Data always needs a join entity in the model.
- Leaving out an inverse only costs you a way to navigate back.
- A to-many relationship comes back as a Swift array in insertion order.
- The missing-inverse warning is cosmetic and nothing changes at runtime.