Articles
Core Data Interview Questions: Contexts, Background Imports, and Merge Conflicts
Prepare for Core Data interviews with context ownership, background-import save paths, object IDs, merge conflicts, batch updates, and targeted practice.
A background import finishes and reports a successful save. The list on screen still shows old values. Meanwhile, a user’s unsaved note disappears after you enable a merge policy. These symptoms can coexist: writing data, making another context observe it, and deciding which conflicting edit wins are separate responsibilities.
Core Data interview questions become easier when you trace one record through those responsibilities. Start by naming the contexts and their queues. Then identify the destination of each save, the mechanism that updates the reader, and the application rule for conflicting fields. “Use a background thread” leaves most of that design unanswered.
Evidence boundary: Framework behavior below is grounded in Apple documentation. The import scenario, troubleshooting sequence, and field-ownership recommendations are original engineering analysis. No candidate reports or employer-specific interview process are claimed.
What does a managed object context actually own?
A context manages an object graph and pending changes within a concurrency domain. Two contexts can represent the same persisted record with different managed object instances and different in-memory values. Apple’s NSManagedObjectContext reference describes both this role and the distinction between a coordinator-backed context and a child context.
Consider an app importing articles from a server. The view context drives the list and an editor. A background context fetches existing records, creates missing ones, and updates server fields. Both may refer to article A17, but that does not make their object instances interchangeable.
Draw the topology before discussing performance. Does the import context share the persistent store coordinator with the view context? Or is it a child of the view context? Those arrangements have different save paths. A statement such as “the background context saved” is incomplete until the diagram shows where its changes went.
Also separate a Core Data object ID from a business identifier. A remote article ID is useful for deduplicating feed records. An NSManagedObjectID identifies an object within the Core Data persistence system. Neither automatically supplies the other’s meaning, and neither specifies which version of a server record is newer.
An answer that begins with these identities avoids a common design failure: importing a second managed object whenever the same remote item arrives again, then trying to solve duplicate rows through UI refreshes.
How should you move work and references across queues?
Apple’s background-use guidance specifies queue confinement for contexts and their managed objects. A container’s view context uses the main queue; its background-task contexts use private queues. Schedule managed-object work through the appropriate context API, and transfer object IDs instead of managed object instances across queues.
Downloading and decoding a response can produce plain value data before entering the import context. Inside the context’s execution block, resolve records, modify managed properties, and save. At the boundary back to the UI, pass an identifier or an immutable result that does not expose queue-confined objects.
A compact ordinary-import sketch looks like this:
let taskContext = container.newBackgroundContext()
try await taskContext.perform {
// Resolve each DTO by remote ID in taskContext.
// Update server-owned fields on taskContext objects.
if taskContext.hasChanges {
try taskContext.save()
}
}
The comments are intentional: the entity mapping, deduplication query, and conflict rules depend on the app’s model. This is a queue-and-save sketch, not a complete importer. Fetching with the view context inside that closure would still use the wrong ownership boundary.
For a newly inserted object, check whether its object ID is temporary. Apple’s obtainPermanentIDs(for:) reference explains that obtaining a permanent ID does not itself save the inserted object. For a sibling context to resolve an ordinary new record, save through the persistence path first, then resolve the ID on the receiving context’s queue. Handle resolution failure if the record has since been deleted.
Saying “the ID is permanent, so everyone can fetch it now” confuses identity allocation with persistence. In an interview, explicitly describe when the record becomes available to the intended reader.
Does saving a child context write to disk?
Apple documents that a context save commits changes one level upward. A child save pushes changes to its parent; persistence requires saving the root context. This is the save-propagation rule in the context reference, rather than an implementation guess based on thread names.
| Topology | Import save reaches | What still needs attention |
|---|---|---|
| Background context attached to the coordinator | Its persistent store through the coordinator | Reader visibility and conflicting edits |
| Background child of another context | Parent’s in-memory object graph | Parent/root save, then reader visibility |
| Several nested contexts | Next parent only | Every required save along the ancestry |
Here is an original verification exercise: insert one record in a child, save only the child, and query from an independent coordinator-backed reader. Then save the parent and repeat the query. With an in-memory persistent store, the local fixture for this guide observed zero records before the parent save and one afterward. The result checks save propagation, not physical disk durability.
For a real application, add a persistent-store reopen test. A list showing a new item before termination does not prove the intended save reached persistent storage. Conversely, a saved item absent from an existing list does not prove the write failed.
A parent context can be useful for discardable edits, but choose it for those semantics. If importing into a main-queue parent, also consider the work that must happen on that parent’s queue. A private child is not a promise that every part of the save path avoids the UI queue.
Why can the UI stay stale after a successful background save?
The view context needs a synchronization strategy. Apple’s automaticallyMergesChangesFromParent property covers automatically merging changes saved to a context’s coordinator or parent. Its name therefore does not mean it applies only to nested child-parent designs.
For an ordinary sibling-context import, automatic merging can be a reasonable starting point. But ask what the UI should do while the user edits the same record. Refreshing a list and preserving an editing draft are different product requirements. A merge policy is not a substitute for deciding how the editor represents unsaved input.
When diagnosing staleness, follow the record rather than toggling flags at random:
- Confirm the importer reached the intended store and saved without error.
- Inspect whether the receiving context consumed the relevant changes.
- Check whether the UI observes that receiving context or displays a detached value copy.
- Check the fetch predicate and sort order; an updated record may legitimately leave the list.
- Inspect any pinned read generation or explicit draft state that intentionally delays new values.
This sequence is original debugging guidance. It separates persistence, context synchronization, and presentation so that evidence from one layer does not masquerade as evidence about all three.
Avoid resetting the view context merely to force a refresh when it contains user edits. Apple’s reset reference describes discarding the context’s managed objects. If a reset is appropriate for a disposable import context, stop using its old managed objects afterward. An editor needs a more deliberate recovery path.
How do you explain merge conflicts without promising the wrong winner?
Apple’s archived Change Management guide explains snapshot-based optimistic locking and the standard policies. Under an error policy, conflicting saves can fail; property-based store-trump and object-trump policies resolve conflicting properties with different priorities. The archive supports these fundamentals, but use current API documentation for contemporary stack configuration.
Use a concrete record to explain the application decision:
Initial: title = "Old title", note = ""
Server import: title = "Corrected title"
Local editor: note = "Read with the team"
The desired combined result is a corrected server title and the user’s note. Now change the case: both contexts edit title. “Merge the changes” no longer identifies a unique desired outcome. Is title server-owned, user-customizable, or subject to a review prompt? State that rule before naming the policy.
| Field or operation | Example ownership decision | Import behavior to discuss |
|---|---|---|
| Server title | Server owns canonical text | Update only when the incoming revision is acceptable |
| Personal note | User owns the field | Importer does not assign it |
| Same-field concurrent edit | User can override the server | Preserve a draft or expose a conflict workflow |
| Server deletion | Product rule still needed | Decide what happens to an open editor and local notes |
This table is an original design recommendation. Property-level framework conflict resolution does not implement arbitrary remote revision ordering, field ownership, or business approval rules.
To reproduce a stale-save conflict, make both contexts actually read the old property values before one saves. Merely fetching an object that remains a fault may defer loading its values; the second context might then materialize a fresh value later. The local fixture initially exposed exactly that distinction. After explicitly reading both old titles, the later conflicting sibling save failed under the error policy as intended.
That is a stronger interview explanation than “two contexts always conflict.” Timing, loaded snapshots, changed properties, and configured policy all matter.
What changes for large imports, batch operations, and retries?
Apple’s large-feed sample uses background work, batch insertion, and persistent history to bring relevant store changes into the view context. Batch operations should not be treated as ordinary edits to already registered managed objects; describe how readers discover their effects.
For a proposed batch importer, specify the result information or persistent-history path used for synchronization. Keep a history token only after consuming the corresponding transactions successfully. If multiple consumers exist, define whose progress the token represents and how history cleanup respects lagging consumers. These are operational design questions, not guarantees supplied by the word “batch.”
Retries require a separate identity rule. If a page download succeeds, its records save, and the progress marker fails, the same page can arrive again. Use the remote identifier to resolve existing records and apply an explicit revision rule. A unique constraint may detect duplicates, but the application still has to define the outcome of competing imports and handle save errors.
Choose a batch boundary that matches recovery requirements. Saving every record may be expensive; saving an entire huge feed can increase pending work and retry scope. A chunked design should record which chunk is committed, what happens after cancellation, and which managed references become invalid after cleanup. Do not claim that one batch size is universally fastest without measuring the actual store and device.
Five related practice questions
The current catalog does not provide five dedicated Core Data questions. These verified Swift, iOS, and concurrency exercises develop adjacent skills; use the context and import scenarios above for Core Data-specific rehearsal.
| Practice question | Connection to this preparation |
|---|---|
| Explain Swift memory, value semantics, and GCD | Explain value DTOs, reference ownership, and execution queues. |
| Explain iOS ARC and avoid retain cycles | Review importer callbacks and observer lifetimes. |
| Design an iOS Timer App with Consistent State and Asynchronous UI Updates | Separate background events from main-queue presentation state. |
| Implement an iOS scrollable grid with navigation | Explain how visible items track an underlying data source. |
| Design document-tag classes with concurrency safety | Define ownership and consistency before adding concurrency. |
Rehearse the save diagram first, then add a conflicting edit and a repeated import page. Use the Software Engineer collection for the surrounding fundamentals rather than claiming these questions are a Core Data assessment syllabus.