In Core Data, why does memory keep climbing while an export walks all 600 students and their courses, and how does refresh(_:mergeChanges:) bring it down?
answer
- fired faults stay filled
- related objects hold each other
- turn objects back into placeholders
- false discards, true reapplies
- refreshAllObjects every batch
basics
~20 sEvery fault the export fires stays filled, and filled objects hold strong references to the related objects they reached, so the graph grows. refresh(_:mergeChanges: false) turns an object back into a fault and breaks those references, letting the graph be released.
solid answer
~40 sBy default a context keeps strong references only to objects that are inserted, updated, deleted or locked (`retainsRegisteredObjects` is false), so clean objects live as long as something else holds them. In an export, realised relationships do: a filled Student references its Courses, which reference their students back through the inverse, so the visited graph keeps itself alive. `context.refresh(student, mergeChanges: false)` turns the student back into a fault, discards its pending changes and, per Apple's documentation, breaks its strong references to related objects, so that part of the graph can be released. `refreshAllObjects()` refreshes every registered object, refaulting clean ones and keeping unsaved edits. With `mergeChanges: true`, Core Data instead reloads the values and reapplies local changes; that is for freshness, not memory.
code
swift · 18 linesimport CoreData
func exportReportCards(context: NSManagedObjectContext) throws -> [String] {
let request = NSFetchRequest<Student>(entityName: "Student")
request.sortDescriptors = [NSSortDescriptor(key: "name", ascending: true)]
request.fetchBatchSize = 50
var lines: [String] = []
for (index, student) in try context.fetch(request).enumerated() {
let titles = (student.courses as? Set<Course>)?.compactMap(\.title) ?? []
lines.append("\(student.name ?? ""): \(titles.sorted().joined(separator: ", "))")
// Every 50 rows, turn what was loaded back into faults so the
// students and their courses can be released.
if index % 50 == 49 {
context.refreshAllObjects()
}
}
return lines
}go deeper
Know that objects you have read stay loaded, and that a context can turn them back into faults to save memory.
Explain the two values of mergeChanges: false discards pending changes and refaults, true reloads and reapplies local changes.
Diagnose climbing memory in a long loop as a self-retaining graph of filled objects, and fix it with batched fetching plus refreshAllObjects() or refresh with false.
Set a rule for long-running jobs over the store, such as batched fetching with refaulting per batch, so exports and imports have a known memory ceiling.
## Why the graph grows An export that writes a report card per student reads `student.name`, traverses `student.courses` and reads each course's `title`. Each read **fires a fault**, filling the object, and a filled object keeps its values until something turns it back into a fault. Three facts combine: - **Fired faults stay filled.** Nothing in the export refaults them; the context's `stalenessInterval` decides whether a later fault uses cached data, and it does not touch objects in use. - **Related objects hold each other.** A filled `Student` holds its resolved `courses`, and each `Course` holds its resolved `students` through the inverse. The visited part of the graph can form strong reference cycles. - **The context is not the only owner.** Apple's documentation for `retainsRegisteredObjects`, false by default, says a context keeps strong references to registered objects only while they are inserted, updated, deleted or locked. Clean objects stay alive because of your references and the references between related objects. So even when the export drops its own references, the students and courses it touched keep one another alive, and memory climbs with every row. ## refresh(_:mergeChanges:) with false `NSManagedObjectContext.refresh(_:mergeChanges:)` takes an object and a flag. With **false**: 1. The context **discards the object's pending changes**. 2. The object **becomes a fault**; the next access reloads its values from the store or the last cached state. 3. Its **transient property values are disposed of**. 4. Its **strong references to related managed objects are broken**. Apple's documentation says you can use this to release a portion of the object graph when you want to constrain memory. The object stays registered with the context, as a placeholder, and the objects it was holding can be released once nothing else holds them. ## refresh(_:mergeChanges:) with true With **true**, the context reloads the object's property values from the store or the cache and then **applies the local changes over them**. The documentation states that this merge always succeeds and never produces a merge conflict, and that transient properties are left alone. Its purposes are **freshness**, when several contexts share a store, and resolving an optimistic locking failure before saving again. It is not the memory tool. | Flag | Pending changes | Object afterwards | Typical use | |---|---|---|---| | `false` | Discarded | A fault | Trimming the graph | | `true` | Reapplied over fresh values | Filled with merged values | Picking up another context's saves | If you call it before `stalenessInterval` has expired, the reload comes from the cache instead of the store. The default staleness interval is infinite. ## refreshAllObjects() for batch work `refreshAllObjects()` calls `refresh(_:mergeChanges:)` on every registered object, and its header notes that it handles objects with unsaved changes. Run against a context with one edited object, it keeps that object's edit and turns the clean objects back into faults. That makes it the simple tool for a long loop: - Fetch with a `fetchBatchSize`, so students load a batch at a time. - Every batch, call `refreshAllObjects()` to refault what the batch filled. - Keep no array of filled objects of your own across batches, or they stay alive whatever the context does. `reset()` is the blunter option: it drops every registered object, and any you still hold become unusable, so it suits a context used only for that job. ## Things to know around refaulting - `willTurnIntoFault()` and `didTurnIntoFault()` run on the object as it is refaulted. Apple suggests clearing custom caches in `didTurnIntoFault()`. - Do not refault an object with `false` if it has edits you mean to keep; check `hasChanges` on the object or use `refreshAllObjects()`. - `shouldRefreshRefetchedObjects` on a fetch request updates fetched objects with current store values, a convenient alternative to refreshing many objects with `true` for freshness. - A refaulted object still answers `objectID` without firing, so code that needs a student again later can keep the ID instead of the object. - Turning a list's objects into faults while they are on screen means reloading their values the next time a cell reads them. ## Putting it together The export's memory problem is not a leak in the usual sense: it is a graph of filled objects that hold one another. Refaulting with `false` or `refreshAllObjects()` cuts those references in batches, so the export's memory stays flat at roughly one batch's worth.
- In Core Data, what happens to a student's unsaved name edit if you call refresh(student, mergeChanges: false)?It is discarded. The student becomes a fault, and the next read of `name` returns the value from the store or the last cached state. Use `mergeChanges: true` or `refreshAllObjects()` if pending edits must survive, or save first.
- In Core Data, why does refreshing objects not help if the export collects them in an array?Refaulting breaks the references between related objects, but your array still holds each Student strongly, and each one stays registered as a fault. Keep only the values you need, such as strings or object IDs, so the objects themselves can be released after each refresh.
- A managed object context always holds every fetched object strongly until reset.
- refresh(_:mergeChanges: true) is the call that frees memory.
- Turning an object into a fault deletes it from the context.
- refresh(_:mergeChanges: false) keeps the object's unsaved changes.
- Faults that have fired are released automatically once the stalenessInterval passes.