The Core Data stack

Persistence Mid-level Swift 5.0+ iOS 17+ Reviewed By Alok Singh

Order the steps

Order the layers from your code down to the disk.

  • NSManagedObject
  • NSPersistentStoreCoordinator
  • NSPersistentStore (SQLite)
  • NSManagedObjectContext
Hint 1 of 1

Start with what your code touches.

Choose an answer, then open Show answer below to check it.

Show answer

Answer: A D B C

  1. NSManagedObject The objects your code reads and changes.
  2. NSManagedObjectContext Tracks changes to those objects until you save.
  3. NSPersistentStoreCoordinator Connects contexts to stores using the model.
  4. NSPersistentStore (SQLite) The file where data actually lives.

30-second answer

Your code works with NSManagedObject instances inside an NSManagedObjectContext, a scratchpad that tracks changes until you save. The context talks to an NSPersistentStoreCoordinator, which maps the managed object model to one or more NSPersistentStores, usually SQLite. NSPersistentContainer sets this up and gives you a main-queue viewContext and background contexts.

Practise saying it · 45 s. No recording, just a timer

Explain the Core Data stack.

Say your answer out loud, then check which of these points you covered:

  • Objects in a context
  • Coordinator and model
  • Stores on disk
  • NSPersistentContainer

Deep dive

The managed object model (.xcdatamodeld) describes entities and relationships.

Faulting loads object data lazily.

NSFetchedResultsController drives table and collection views from fetches.

NSPersistentCloudKitContainer adds CloudKit sync.

Common mistakes

  • Treating managed objects as plain value types.
  • Saving the context after every tiny change.

Senior take & follow-ups

Seniors explain each layer's job and where threading rules apply.

Follow-up questions

Think of your answer first, then open the hint.

  1. What is a fault?

    Show hint

    A placeholder whose data is loaded on first access.

  2. What does NSPersistentContainer give you?

    Show hint

    The stack, a viewContext and background contexts.

Suggest a fix if something here is wrong or out of date.