skip to content

In Core Data, which delete rules make deleting a Course remove its Lessons but keep its Students, and what does each rule do?

level: middleimportance: must knowfreq 70%

answer

  1. a rule per relationship, per direction
  2. the default is not cascade
  3. who owns whom, and who is shared
  4. deny fails the save, not the delete call
  5. no action leaves the other side pointing

basics

~20 s

Set Course.lessons to Cascade and Course.students to Nullify. Nullify clears the deleted object from the other side, Cascade deletes the destination objects too, Deny refuses the delete while destinations exist, and No Action changes nothing on the other side.

solid answer

~40 s

In Core Data each relationship carries its own `deleteRule`, applied when the object that owns that relationship is deleted; the default is `.nullifyDeleteRule`. So on Course, `lessons` is **Cascade**, because lessons belong to one course, and `students` is **Nullify**, which removes the course from each student's `courses` set. On the other side, `Lesson.course` and `Student.courses` stay Nullify: Cascade on `Student.courses` would delete shared courses for everyone. **Deny** fits `Teacher.courses`: `context.delete(teacher)` returns normally, but `save()` fails with `CocoaError.validationRelationshipDeniedDelete` while the teacher still has courses. **No Action** does nothing to the destinations, leaving their inverse pointing at a deleted object for your code to fix.

code

swift · 17 lines
swift
import CoreData

enum DeleteOutcome { case deleted, stillTeaches, failed(Error) }

func deleteTeacher(_ teacher: Teacher, in context: NSManagedObjectContext) -> DeleteOutcome {
    context.delete(teacher)  // Teacher.courses uses the Deny rule
    do {
        try context.save()
        return .deleted
    } catch let error as CocoaError where error.code == .validationRelationshipDeniedDelete {
        context.rollback()  // the teacher still has courses, so undo the delete
        return .stillTeaches
    } catch {
        context.rollback()
        return .failed(error)
    }
}

go deeper

for a junior

Recall the four rules and that the default is Nullify, and know that Cascade suits owned children such as a course's lessons.

for a middle

Explain that rules are set per direction, walk through what each one leaves behind, and show that Deny fails at save with a validation error rather than at delete.

for a senior

Spot Cascade on the shared side of a many-to-many in review, explain how cascades chain, and know that Deny does not combine with a batch delete request.

for a principal

Agree on an ownership map for the model so every delete rule follows from it, and require a named owner for any No Action relationship.

## Where a delete rule lives In Core Data a **delete rule** belongs to one relationship in one direction. It is the `deleteRule` property of an `NSRelationshipDescription`, chosen in the model editor's Delete Rule pop-up, and it answers one question: when the object that owns this relationship is deleted, what happens to the objects at the other end? The default, per Apple's documentation, is `.nullifyDeleteRule`. Because rules are per direction, `Course.lessons` and `Lesson.course` each have their own. Deleting a Lesson applies `Lesson.course`'s rule; deleting a Course applies `Course.lessons`'s rule. ## The four rules | Rule | Swift constant | What happens to the destinations | |---|---|---| | Nullify | `.nullifyDeleteRule` | They stay; the deleted object is removed from their inverse | | Cascade | `.cascadeDeleteRule` | They are deleted too, and their own rules then run | | Deny | `.denyDeleteRule` | The delete is refused while any destination exists | | No Action | `.noActionDeleteRule` | Nothing; their inverse still points at the deleted object | - **Nullify** is the safe default for shared or independent objects. Deleting a Course with `students` set to Nullify leaves every Student in place and takes the course out of each student's `courses`. It relies on the inverse: without one there is nothing to nullify. - **Cascade** expresses ownership. A Lesson has no meaning without its Course, so `Course.lessons` cascades, and each deleted lesson's own rules run in turn. - **Deny** protects a parent that must be emptied first. With `Teacher.courses` set to Deny, a teacher who still teaches courses cannot be removed. - **No Action** leaves the graph inconsistent on purpose. It exists for cases where your code repairs the other side itself; otherwise the destination keeps a reference to a deleted object, which later reads as an inaccessible fault. ## Rules for the timetable model 1. `Course.lessons`: **Cascade**, because lessons are owned by their course. 2. `Lesson.course`: **Nullify**, so deleting one lesson only removes it from its course. 3. `Course.students` and `Student.courses`: **Nullify** on both sides, because neither owns the other. 4. `Teacher.courses`: **Deny**, so courses are reassigned before a teacher leaves. 5. `Teacher.office`: **Cascade** if the office record exists only for that teacher, and `Office.teacher`: **Nullify**. The classic mistake is Cascade on the shared side of a many-to-many. If `Student.courses` cascades, deleting one student deletes every course they took, and Course's own Cascade then deletes those courses' lessons, for every other student too. ## When the rules run and how Deny fails `context.delete(_:)` marks the object deleted. Core Data propagates delete rules when it processes pending changes (`propagatesDeletesAtEndOfEvent` defaults to true) and at the latest during `save()`. **Deny is enforced as validation**: the documentation for `validateForDelete()` says an object cannot be deleted if a relationship with a Deny rule has a destination object. So the delete call returns normally and the error arrives from `save()`: - The error is a `CocoaError` with code `.validationRelationshipDeniedDelete`, numeric value 1600. - If several validation errors happen in one save, they arrive wrapped together as one multiple-validation error, so check the detailed errors too. - The delete is still pending in the context: `rollback()` undoes it, or you reassign the courses and save again. ## Hooks and validation around a delete - `prepareForDeletion()` runs on the deleted object before delete propagation, while its relationships are still intact. Apple's documentation suggests it for custom propagation before relationships are torn down, such as clearing a No Action reference by hand. - Nullify can break a **count rule**. If a non-optional `Course.lessons` has a `minCount` of 2, deleting one of a course's two lessons leaves it below the minimum, and the save fails with `CocoaError.validationRelationshipLacksMinimumCount`. The header notes that counts are only enforced when the relationship is not empty, so an optional relationship can still drop to zero. - A save that fails validation writes none of its changes, so one refused delete holds back everything else in that save. ## Batch deletes and rules An `NSBatchDeleteRequest` works on the store, not on managed objects in a context, and Apple's documentation states that the Deny rule is not compatible with it. If a model relies on Deny, a batch delete is the wrong tool for that entity. (How batch requests reach the context is covered with managed object contexts.) ## How to pick a rule - Ask **who owns whom**: an owner cascades to what it owns, never the reverse. - Ask **what is shared**: shared objects get Nullify. - Ask **what must be emptied first**: that parent gets Deny, and the UI explains why the delete failed. - Treat **No Action** as a code-review question: name the code that repairs the other side, or switch to Nullify.

  • In Core Data, what does a No Action rule on Teacher.mentees leave on each Student when the Teacher is deleted?
    Nothing on the students changes, so each `student.mentor` still refers to the deleted teacher. After the save, traversing it meets an inaccessible fault; with `shouldDeleteInaccessibleFaults` at its default of true, the context hands back an object marked deleted with nil attributes. Your code must clear `mentor` itself, which is why Nullify is the usual choice.
  • In Core Data, why can Cascade on a to-many relationship delete more than you expected?
    Cascade deletes every destination object and then runs their own delete rules, so the effect chains. Cascade on `Student.courses` deletes each shared course, and `Course.lessons`'s Cascade then deletes those courses' lessons. Cascade only from an owner to what it exclusively owns.
  • In Core Data, when do you see the Deny rule's error?
    At `save()`. `delete(_:)` only marks the object; Deny is enforced as validation, so the save throws a `CocoaError` with code `.validationRelationshipDeniedDelete`, or a multiple-validation error that contains it. Roll back or reassign the courses, then save again.

  • Core Data's default delete rule is Cascade, so related objects disappear by default.
  • Cascade on both sides of a many-to-many is fine because Core Data only deletes unshared objects.
  • A Deny rule makes context.delete(_:) throw immediately.
  • No Action is the same as Nullify without the extra work.
  • One delete rule covers both directions of a relationship pair.