skip to content

In Core Data, what is a fault, what makes one fire, and what does isFault tell you about a fetched Student?

level: middleimportance: must knowfreq 66%

answer

  1. a placeholder with a real identity
  2. fetches return them by default
  3. reading a persistent property fires it
  4. true does not mean not in memory
  5. relationships are faults of their own

basics

~20 s

A fault is a managed object, or a relationship, whose values Core Data has not loaded into it yet. Reading a persistent property fires it. isFault true means the object is still a placeholder; false means its data is in memory.

solid answer

~40 s

A fetch returns its objects as **faults** by default, because `returnsObjectsAsFaults` defaults to true: each Student is a real `NSManagedObject` with its `objectID` and entity, while its values wait in Core Data's row cache. Reading a persistent property such as `student.name` **fires** the fault and fills the object; asking for `objectID`, `entity`, `isDeleted` or `isFault` itself does not. When `isFault` is false the data is in memory. When it is true, the documentation is careful: the data may or may not be cached, so it means only that this object has not been filled. Relationships fault separately: `student.courses` stays a fault until traversed, and `hasFault(forRelationshipNamed:)` tells you without firing it.

code

plaintext · 4 lines
plaintext
<NSManagedObject: 0x78694e8050> (entity: Student; id: 0xb0e2d0c17f40dbb9 <x-coredata://137E573F-E722-4E49-B8F1-94EAC96179B5/Student/p1>; data: <fault>)
<NSManagedObject: 0x78694e8050> (entity: Student; id: 0xb0e2d0c17f40dbb9 <x-coredata://137E573F-E722-4E49-B8F1-94EAC96179B5/Student/p1>; data: {
    name = B;
})

go deeper

for a junior

Recall that fetched objects start as faults, that reading a property fills them in, and that seeing data: <fault> in the debugger is normal.

for a middle

Explain the row cache, which members are safe on a fault, the two halves of isFault, and that relationships fault separately from the object.

for a senior

Use hasFault(forRelationshipNamed:) and isFault to keep optional work from growing the graph, and recognise key-value coding over a collection as a hidden source of fault firing.

for a principal

Make faulting part of the team's performance review vocabulary, so list and export code is checked for what it fires per row before it ships.

## What a fault is Core Data does not load a whole object graph when you fetch. It hands you **faults**: managed objects that exist, with their entity, their context and an `NSManagedObjectID`, but whose property values have not been put into them yet. Apple's documentation for `NSManagedObject` describes a fault as an object whose property values haven't yet been loaded from the external data store. Faulting is how a context can hold references to thousands of objects without paying for all their data. There are two kinds: - **Object faults**: a Student whose attributes, such as `name`, are not filled in yet. - **Relationship faults**: a Student whose `courses` relationship has not been resolved to its Course objects yet. A student can be filled while its relationships are still faults. ## Where faults come from 1. **Fetches.** `NSFetchRequest.returnsObjectsAsFaults` defaults to true. The documentation says Core Data fetches the matching rows, fills its **row cache**, and returns the objects as faults; firing one later reads from that cache. 2. **Object IDs.** `object(with:)` on a context returns the registered object, or a fault for that ID; it never returns nil and does no I/O, so a wrong ID only shows up when the fault fires. `existingObject(with:)` throws instead and never returns a fault. 3. **Relationships.** Traversing `student.courses` gives you course objects that are themselves faults until you read them. 4. **Refreshing.** `refresh(_:mergeChanges:)` with false turns a loaded object back into a fault. ## What fires a fault and what does not Reading or writing a **persistent property** fires the fault: `student.name`, `student.courses`, `value(forKey:)`. Apple lists the members that are safe on a fault: `isEqual(_:)`, `hash`, `description`, `managedObjectContext`, `entity`, `objectID`, `isInserted`, `isUpdated`, `isDeleted`, `faultingState` and `isFault`, among others. Because equality and hashing do not fire, managed objects can sit in sets and dictionaries cheaply. Two traps follow from that list: - A custom `description` that reads attributes fires the fault, and Apple strongly discourages overriding it that way. The default description prints `data: <fault>` for an unfired object. - Key-value coding on a collection, such as `value(forKey: "name")` on an array of students, can call `value(forKey:)` on each object and so fire every fault, as Apple's documentation warns. ## Laziness in layers Faults are one of several ways a fetch avoids loading what you might not read: - With `fetchBatchSize` set, the fetch records every match's identity but loads data a batch at a time; the header describes the returned array as a subclass that faults batches on demand. - With `includesPropertyValues` set to false, the fetch obtains only what it needs to build object IDs, so firing each fault later costs a store access. - With `returnsObjectsAsFaults` at its default, the data is in the row cache and firing reads it from there. ## Reading isFault correctly | `isFault` | What you can conclude | |---|---| | `false` | The object's data is in memory | | `true` | The object has not been filled; its data may still be in the row cache | The documentation for `isFault` states both halves: if false, the data must be in memory; if true, it does not mean the data is not in memory. Reading `isFault` never fires the fault. Use it when work is optional, for example to skip a derived value for objects the user has not opened. For relationships, `hasFault(forRelationshipNamed:)` answers the same question for one relationship and does not fire it. ## Faults and the object's life cycle - `awakeFromFetch()` runs after a fetch or after unfaulting, so it suits derived values computed from persistent properties. - `willTurnIntoFault()` and `didTurnIntoFault()` run when an object is turned back into a fault. Apple suggests `didTurnIntoFault()`, not `deinit`, for clearing custom caches. - **Uniquing**: within one context, one record is one managed object instance, so a fetch or a relationship that reaches a student you already hold returns that same instance. ## Why it matters in interviews Faulting explains several things a candidate will meet: why a fetched object prints `<fault>` in the debugger, why touching one property in a loop costs a store round trip per object, and why reading a related object's name can be slower than reading the object's own. The usual fix for that last cost is to name the relationship in the fetch request's `relationshipKeyPathsForPrefetching`. The core idea is that a fault is a cheap placeholder that becomes a full object on first access.

  • In Core Data, what does setting returnsObjectsAsFaults to false on a fetch request change?
    The fetched objects come back already filled with their attribute values, so `isFault` is false and reading attributes skips the fault-firing step. Their to-many relationships are still faults, though: traversing `student.courses` still costs a store query per student. Loading related objects up front is what `relationshipKeyPathsForPrefetching` does.
  • In Core Data, what is the difference between object(with:) and existingObject(with:) on a context?
    `object(with:)` returns the registered object or a fault for that ID, never nil and without I/O; if the record no longer exists, the problem appears when the fault fires. `existingObject(with:)` throws if the object cannot be fetched, may perform I/O, and never returns a fault, so it suits IDs you are not sure still exist.

  • A fault is an error Core Data raises when it cannot find a record.
  • isFault true means the object's data is definitely not in memory.
  • Reading objectID or isFault on a fault fires it.
  • Setting returnsObjectsAsFaults to false also loads every related object.
  • Printing a managed object in the debugger forces Core Data to load it.