skip to content

In Core Data, what changes when you mark Course.lessons as an ordered to-many relationship, and when is a position attribute the better choice?

level: middleimportance: should knowfreq 38%

answer

  1. a checkbox in the relationship inspector
  2. NSSet becomes NSOrderedSet
  3. indexed accessors appear in codegen
  4. the order is not a sortable attribute
  5. isOrdered has been there since iOS 5

basics

~20 s

An ordered to-many relationship makes Core Data persist the members' order: the property becomes an NSOrderedSet and codegen adds indexed accessors. Use an integer position attribute instead when fetch requests must sort or filter by that order.

solid answer

~40 s

Marking a to-many relationship ordered sets `isOrdered`, which defaults to false and has existed since iOS 5. The generated property changes from `NSSet?` to `NSOrderedSet?`, codegen adds indexed accessors such as `insertIntoLessons(_:at:)`, `removeFromLessons(at:)` and `replaceLessons(at:with:)`, and `mutableOrderedSetValue(forKey:)` lets you move members. Core Data then saves the sequence and gives it back after relaunch, which an unordered set never promises. The cost is that the order belongs to the relationship, not to Lesson: a fetch request for lessons has no attribute to sort or filter by it, so you read it only by traversing `course.lessons`. When a list is driven by fetch requests, store a `position` attribute, sort with an `NSSortDescriptor`, and renumber on reorder yourself.

code

swift · 10 lines
swift
import CoreData

func moveLesson(in course: Course, from source: Int, to destination: Int) {
    let lessons = course.mutableOrderedSetValue(forKey: "lessons")
    lessons.moveObjects(at: IndexSet(integer: source), to: destination)
}

func lessonTitles(of course: Course) -> [String] {
    (course.lessons?.array as? [Lesson] ?? []).compactMap(\.title)
}

go deeper

for a junior

Know that to-many relationships are unordered sets by default and that the Ordered checkbox turns the property into an NSOrderedSet.

for a middle

Explain the generated indexed accessors and mutableOrderedSetValue(forKey:), and why a fetch request cannot sort by the relationship's order.

for a senior

Choose between an ordered relationship and a position attribute from how the list is fetched, how long it is and how often users reorder it.

for a principal

Agree on one ordering pattern for the app's models so list screens, migrations and sync treat order consistently instead of mixing both approaches.

## Unordered by default A **to-many relationship** in Core Data is unordered unless you say otherwise. The generated property is an `NSSet?`, and a set has no sequence: the lessons you read back may come in any order, and that order can differ between launches. If the UI needs them in a teaching order, something has to store it. `NSRelationshipDescription.isOrdered` is that switch. In the model editor it is the **Ordered** checkbox on a to-many relationship. The documentation gives its default as false, and the header marks it available since iOS 5. ## What the Ordered flag changes | Aspect | Unordered (`isOrdered` false) | Ordered (`isOrdered` true) | |---|---|---| | Generated property | `NSSet?` | `NSOrderedSet?` | | Order after relaunch | None promised | The order you saved | | Mutable proxy | `mutableSetValue(forKey:)` | `mutableOrderedSetValue(forKey:)` | | Generated accessors | add and remove, single object or set | the same, plus indexed insert, remove and replace | | Sorting a fetch by it | Not applicable | Not possible: the order is not an attribute | With codegen on, an ordered `lessons` relationship gets Swift accessors like these, each bridged to the key-value coding name Core Data expects: - `insertIntoLessons(_:at:)`, for inserting at a position, in a single-lesson form taking an `Int` and an array form taking an `NSIndexSet`. - `removeFromLessons(at:)`, to remove by index. - `replaceLessons(at:with:)`, to swap a member in place. - `addToLessons(_:)` and `removeFromLessons(_:)`, which append or remove by identity. Every one of these goes through Core Data's change tracking, so the inverse `Lesson.course` stays in step and the new order is saved with the next `save()`. ## Reordering in practice To let a teacher drag lesson 4 to the top, take the mutable ordered proxy and move the member: ```swift let lessons = course.mutableOrderedSetValue(forKey: "lessons") lessons.moveObjects(at: IndexSet(integer: 3), to: 0) ``` Reading the order back means converting the ordered set: `course.lessons?.array as? [Lesson]`. A Swift array is not what the property holds, so code that assumes `[Lesson]` must convert first. ## How the accessors and the proxy fit together The generated Swift methods carry `@objc` names such as `insertObject:inLessonsAtIndex:` and `removeObjectFromLessonsAtIndex:`. Those are the key-value coding patterns that `mutableOrderedSetValue(forKey:)` looks for: Foundation's header describes the proxy searching for `-insertObject:in<Key>AtIndex:` and `-removeObjectFrom<Key>AtIndex:` and sending its edits through them. So the proxy and the generated accessors are two routes into the same change-tracked methods. Only the to-many side is ordered. The inverse, `Lesson.course`, stays a plain to-one relationship, and assigning `lesson.course = course` appends the lesson to the end of the ordered set. An ordered relationship also faults like any other to-many: nothing about its members loads until you traverse it. ## What it costs 1. **The order lives on the relationship.** It is not an attribute of Lesson, so a fetch request for Lesson cannot name it in a sort descriptor or a predicate. A list driven by a fetch request, including one an `NSFetchedResultsController` runs, cannot follow it. 2. **Core Data persists the new sequence on every insert or move.** That is convenient, but on a long relationship that users reorder often it adds write work to each save. 3. **You must remember it is a set.** An `NSOrderedSet` holds each object once; adding a lesson that is already in it does not duplicate it. ## The alternative: a position attribute Keep `lessons` unordered and give Lesson an integer attribute such as `position`: - A fetch request sorts by it with `NSSortDescriptor(key: "position", ascending: true)`, and can filter on it. - The order is plain data, visible in the model and handled like any other attribute when the model changes. - The cost is yours: on reorder, your code renumbers the affected lessons. ## Choosing - The order is read only by walking from the parent, and edits are drag-and-drop on a short list: an **ordered relationship** keeps the code small. - The order drives fetches, sections or filters, or the list is long and reordered often: a **position attribute** keeps the order queryable. - The position means something of its own, such as a week number or a timetable slot: model it as data, on Lesson or on a join entity, not as relationship order.

  • In Core Data, can an NSFetchedResultsController list a course's lessons in the ordered relationship's order?
    Not directly. The controller runs a fetch request, and a fetch request sorts by attributes; the position inside an ordered relationship is not an attribute of Lesson. Either read `course.lessons` and drive the list yourself, or store a `position` attribute and sort the fetch by it.
  • In Core Data, what happens if you call addToLessons(_:) with a lesson that is already in the ordered relationship?
    The relationship is an ordered set, so the lesson appears only once and is not duplicated. To show the same lesson twice in a timetable you need a separate object for each occurrence, such as a scheduled-slot entity pointing at the lesson.

  • An unordered to-many relationship returns its members in insertion order.
  • Marking a relationship ordered lets fetch requests sort by that order.
  • An ordered to-many relationship is generated as a Swift array of the destination type.
  • An ordered relationship can hold the same object twice.
  • Ordered relationships need iOS 17 or a newer release.