Skip to content
Commitwise
Menu
iOS Development

Core Data in existing apps

Work safely with the Core Data stack in the many apps that still use it, with the view context on the main queue, background contexts with perform, object IDs across threads, merge policies and unique constraints, then fetch efficiently, run migrations without crashing at launch, keep batch operations and extensions in sync, and plan a move to SwiftData.

advanced

The core idea with one simple example.Step by step, with more examples and exercises.A cheat sheet: key APIs, gotchas and trade-offs.Internals, trade-offs and production pitfalls.

You join a team whose app is eight years old. It stores everything in Core Data: notes, attachments, sync state. The crash list has EXC_BAD_ACCESS in -[NSManagedObject valueForKey:], a “could not fulfill a fault” exception, and a spike of launch crashes after the last release, in loadPersistentStores. A teammate asks whether it’s time to rewrite everything in SwiftData.

New apps often start with SwiftData, which is built on Core Data. But most large iOS codebases still use Core Data directly, and senior interviews ask about it. Its rules are few and strict: every context has its own queue, objects never cross contexts, and the model changes only through migrations. Break one and you get exactly the crashes above.

New to some of these? Open what you need, or skip ahead.

Basics:What is a persistence framework?

A persistence framework saves your app’s objects to disk and loads them back, so you work with Swift objects instead of writing SQL. Core Data stores them in a SQLite database by default and keeps track of changes, relationships and undo. The structure of your data (entities and their attributes) is described in a model file, .xcdatamodeld.

Basics:What is a thread or queue?

A queue runs pieces of work one after another. The main queue runs on the main thread, where the UI is drawn; other queues run work in the background so the UI stays smooth. Core Data objects belong to one queue, and touching them from another one can crash the app.

Part Not started

The stack, contexts and threads

Core Data has three main pieces:

The rule that prevents most crashes: each context has its own queue, and its objects may only be used on that queue.

  • viewContext belongs to the main queue. Use it for everything the UI shows.
  • Background contexts do heavy work, like importing 5,000 notes from the server, inside perform { }, which runs the code on that context’s own queue.

To give an object to another context, pass its objectID, a stable identifier, and load the object again in the other context.

NSPersistentContainer wires the model, the persistent store coordinator and contexts. The viewContext is a main-queue context for UI reads and small edits; imports, sync and batch work go in newBackgroundContext() or performBackgroundTask, always inside perform/performAndWait (or await context.perform), because every NSManagedObjectContext is confined to its queue and NSManagedObjects aren’t Sendable. Cross-context references go through NSManagedObjectID (permanent after save; call obtainPermanentIDs if you hand off before saving). Set viewContext.automaticallyMergesChangesFromParent = true so background saves propagate, choose a merge policy (NSMergeByPropertyObjectTrumpMergePolicy is the common default: in-memory changes win per property), and model natural keys with unique constraints so inserting an existing id becomes an update instead of a duplicate. Run development builds with -com.apple.CoreData.ConcurrencyDebug 1, which traps on any cross-queue access, turning rare EXC_BAD_ACCESS crashes into immediate, debuggable ones. In SwiftUI, @FetchRequest observes the view context; in UIKit, NSFetchedResultsController drives diffable snapshots.

import CoreData

final class Persistence {
    static let shared = Persistence()
    let container: NSPersistentContainer

    init(inMemory: Bool = false) {
        container = NSPersistentContainer(name: "Notes")
        if inMemory {
            container.persistentStoreDescriptions.first?.url = URL(filePath: "/dev/null")   // tests and previews
        }
        container.loadPersistentStores { _, error in
            if let error { Logger.storage.fault("Store failed to load: \(error)") }   // handled below, not fatalError
        }
        let view = container.viewContext
        view.automaticallyMergesChangesFromParent = true                  // background saves show up in the UI
        view.mergePolicy = NSMergeByPropertyObjectTrumpMergePolicy
    }

    /// Imports server notes off the main thread. `serverID` has a unique constraint, so re-imports update.
    func importNotes(_ dtos: [NoteDTO]) async throws {
        let context = container.newBackgroundContext()
        context.mergePolicy = NSMergeByPropertyObjectTrumpMergePolicy
        try await context.perform {                                       // runs on the context's queue
            for dto in dtos {
                let note = Note(context: context)
                note.serverID = dto.id
                note.title = dto.title
                note.updatedAt = dto.updatedAt
            }
            try context.save()
        }
    }
}

// SwiftUI: reads from the view context and updates when it changes
struct NotesList: View {
    @FetchRequest(sortDescriptors: [SortDescriptor(\.updatedAt, order: .reverse)])
    private var notes: FetchedResults<Note>

    var body: some View {
        List(notes) { note in Text(note.title ?? "Untitled") }
    }
}
  • viewContext is used by @FetchRequest, on the main queue, for the list.
  • newBackgroundContext() + perform does the import on a background queue, so scrolling stays smooth even with thousands of notes.
  • automaticallyMergesChangesFromParent makes the list update by itself when the background context saves.
  • The unique constraint on serverID (set in the model editor, under the entity’s Constraints) plus the merge policy means importing the same note twice updates it instead of creating a duplicate.
Spot the bugA crash once in a thousand imports

Tap the line with the bug.

func importNotes(_ dtos: [NoteDTO]) {
    DispatchQueue.global().async {
        let context = Persistence.shared.container.viewContext
        for dto in dtos {
            let note = Note(context: context)
            note.title = dto.title
        }
        try? context.save()
    }
}

Predict the output

The background import saves 50 new notes. The view context's automaticallyMergesChangesFromParent is false (the default), and the list uses @FetchRequest on the view context. What does the list show right after the save?

Practice: open a note on the main queue from a background result

A background search finds a matching note and should open it in the UI. You can’t pass the Note object to the main queue, but you can pass its objectID:

func findAndOpen(text: String) async throws {
    let context = Persistence.shared.container.newBackgroundContext()
    let id: NSManagedObjectID? = try await context.perform {
        let request = Note.fetchRequest()
        request.predicate = NSPredicate(format: "title CONTAINS[cd] %@", text)
        request.fetchLimit = 1
        return try context.fetch(request).first?.objectID      // an ID, safe to pass around
    }
    guard let id else { return }
    await MainActor.run {
        let viewContext = Persistence.shared.container.viewContext
        if let note = try? viewContext.existingObject(with: id) as? Note {
            router.open(note)                                    // the same note, from the main-queue context
        }
    }
}

existingObject(with:) loads the object in the view context, or throws if it was deleted in the meantime.

Fetching efficiently

  • Faults: fetched objects are placeholders until a property is read; reading a relationship in a loop fires one query per object (the N+1 problem). Use relationshipKeyPathsForPrefetching for relationships you’ll touch.
  • fetchBatchSize (e.g. 20) for long lists: Core Data loads rows in batches as you scroll; @FetchRequest and NSFetchedResultsController respect it.
  • propertiesToFetch / .dictionaryResultType for read-only aggregates, and NSExpression for counts and sums in SQL instead of in memory.
  • Indexes: add fetch indexes in the model for attributes you filter or sort on.
  • -com.apple.CoreData.SQLDebug 1 prints the SQL and timings, the quickest way to spot unbounded fetches.
  • viewContext: main queue, UI. Background work: newBackgroundContext() / performBackgroundTask, always in perform (await context.perform).
  • Objects are confined to their context and not Sendable: pass NSManagedObjectID (permanent after save), reload with existingObject(with:).
  • automaticallyMergesChangesFromParent = true, NSMergeByPropertyObjectTrumpMergePolicy, unique constraints for upserts.
  • -com.apple.CoreData.ConcurrencyDebug 1 in development; SQLDebug for queries.
  • Efficiency: fetchBatchSize, prefetching relationships, fetch indexes, dictionary results and NSExpression for aggregates.

Check this part

  1. Which context should the UI read from?

  2. How do you hand a note found in a background context to the main queue?

  3. What does -com.apple.CoreData.ConcurrencyDebug 1 do?

  4. Re-importing a note with the same serverID should update it. What makes that happen?

NSPersistentContainer sets up the stack. The viewContext runs on the main queue for UI; background contexts do imports and heavy work inside perform. Managed objects belong to their context: pass NSManagedObjectID across, never the object. Turn on automaticallyMergesChangesFromParent and a merge policy, use unique constraints for upserts, and run with -com.apple.CoreData.ConcurrencyDebug 1 in development.

Part Not started

Migrations, batch work and the way forward

The model file describes what’s in the database. When you change it (add an attribute, rename one, add an entity), existing users still have a database in the old shape. Core Data has to migrate it when the new version of the app opens it.

The safe routine:

  1. Add a new model version (Editor → Add Model Version), make it current, and change only the new version.
  2. Keep changes simple where you can: new attributes that are optional or have a default value, new entities, renames marked with a renaming identifier. Core Data migrates those automatically (lightweight migration).
  3. Test with an old database: install the previous app version, add data, then install the new build over it.

If a migration fails, the store doesn’t load. If the app then calls fatalError, as Xcode’s template does, it crashes at every launch until the next update. That’s the launch-crash spike from the start of the lesson.

Model changes require a new model version; lightweight migration (on by default with NSPersistentContainer) infers mappings for additive and rename changes (renamingIdentifier), optional-to-required only with defaults, and some type changes. Anything else, such as splitting an entity, transforming values or deduplicating before adding a unique constraint, uses staged migration (NSStagedMigrationManager, iOS 17) composed of lightweight and custom stages with willMigrate/didMigrate hooks, or a mapping model with NSEntityMigrationPolicy on older targets. Migrations run synchronously when the store loads, so large ones belong behind a launch screen that shows progress, never inline in App.init (watchdog). Test migrations in CI from stores created by every shipped model version. Batch requests (NSBatchInsertRequest, NSBatchUpdateRequest, NSBatchDeleteRequest) operate in SQL without loading objects, so contexts don’t see their changes; request object IDs (resultType = .objectIDs) and merge them with NSManagedObjectContext.mergeChanges(fromRemoteContextSave:into:), or rely on persistent history trackingPersistent history trackingA Core Data feature that records every change to a store, so other contexts and processes can catch up on it.Open in glossary → (NSPersistentHistoryTrackingKey + remote change notifications), which is also how the app picks up writes from widgets, extensions and NSPersistentCloudKitContainer. SwiftData can use the same store and coexist during a gradual migration, but it needs matching entity names, persistent history enabled on both stacks, and careful testing; for a stable Core Data app with complex queries, staying is often the better call.

container.loadPersistentStores { description, error in
    guard let error = error as NSError? else { return }
    Logger.storage.fault("Store load failed: \(error.domain) \(error.code)")
    // Don't fatalError: report it, then recover. A local cache can be rebuilt from the server;
    // user-created data needs a recovery path (keep the old file, show a support screen).
    if let url = description.url, StoreRecovery.isRebuildable {
        try? container.persistentStoreCoordinator.destroyPersistentStore(at: url, type: .sqlite)
        container.loadPersistentStores { _, _ in }
    } else {
        AppState.shared.storageFailure = error
    }
}

// Delete old drafts in SQL, then tell the view context which objects disappeared
func deleteDrafts(olderThan date: Date) async throws {
    let context = container.newBackgroundContext()
    try await context.perform {
        let request = NSFetchRequest<NSFetchRequestResult>(entityName: "Note")
        request.predicate = NSPredicate(format: "isDraft == YES AND updatedAt < %@", date as NSDate)
        let delete = NSBatchDeleteRequest(fetchRequest: request)
        delete.resultType = .resultTypeObjectIDs
        let result = try context.execute(delete) as? NSBatchDeleteResult
        let ids = result?.result as? [NSManagedObjectID] ?? []
        NSManagedObjectContext.mergeChanges(fromRemoteContextSave: [NSDeletedObjectsKey: ids],
                                            into: [self.container.viewContext])
    }
}
  • No fatalError when the store fails to load: the error is logged, and the app either rebuilds a cache it can download again or shows a recovery screen. The user can still open the app.
  • NSBatchDeleteRequest deletes thousands of rows directly in the database, without loading them, which is much faster.
  • Because it skips the contexts, the UI wouldn’t know those notes are gone. mergeChanges(fromRemoteContextSave:into:) tells the view context which objects were deleted, so the list updates.

Predict the output

Version 3 of the model makes the existing optional attribute Note.folder required (non-optional), with no default value. Some users have notes without a folder. They install the update. What happens?

Production puzzles

Spot the bugA fault that can't be fulfilled

Tap the line with the bug.

@MainActor
final class NoteDetailModel {
    let note: Note                          // from the view context

    init(note: Note) { self.note = note }

    var title: String { note.title ?? "" }
}

// Elsewhere, a cleanup job:
let delete = NSBatchDeleteRequest(fetchRequest: Note.fetchRequest())
try backgroundContext.execute(delete)

Predict the output

A widget extension writes 'note pinned' changes to the shared Core Data store in the App Group. The app is running in the background with its own container on the same store. When the user returns to the app, does the pinned state show?

Exercisehard

Plan a move to SwiftData

The team wants to adopt SwiftData for new features in an app with a large Core Data model, a widget, and CloudKit sync through NSPersistentCloudKitContainer. What’s your recommendation and plan?

›

Ask what SwiftData would give this app, what it can’t do yet, and how two stacks would share one store.

SolutionTry it yourself first
  • Start with the why. SwiftData’s benefits are mainly ergonomics (@Model, @Query, macros, Swift concurrency with @ModelActor). The risks: features this app uses that SwiftData handles differently or not at all (complex fetch requests, batch operations, custom migrations, fine-grained CloudKit control), and a second stack on the same data.
  • Recommendation: don’t rewrite. If there’s a strong reason, use coexistence for new, mostly independent entities: both stacks open the same store URL, entity names and versions match, persistent history tracking is on in both, and only one stack writes each entity.
  • Order: enable persistent history in Core Data first and ship it; add SwiftData @Model types mirroring new entities; keep CloudKit sync on the Core Data side; move the widget last.
  • Guardrails: migration tests from every shipped store version, a kill switch to fall back to the Core Data path, and performance comparisons on large datasets.
  • Alternative: keep Core Data and modernize the API around it (async perform, NSManagedObjectID-based view models, @FetchRequest), which brings most of the day-to-day benefit with none of the risk.
Exerciseeasy

Add an attribute safely

Notes need a new isPinned flag. Pinned notes appear first in the list. Describe the model change and the code change, so existing users’ notes migrate without problems.

›

Which kinds of changes can lightweight migration handle by itself?

SolutionTry it yourself first
  1. Editor → Add Model Version (for example Notes 4), and set it as the current version in the File inspector.
  2. In the new version, add isPinned as a Boolean with a default value of NO. Existing notes get false automatically; lightweight migration handles it.
  3. Sort pinned notes first:
@FetchRequest(sortDescriptors: [
    SortDescriptor(\.isPinned, order: .reverse),
    SortDescriptor(\.updatedAt, order: .reverse),
])
private var notes: FetchedResults<Note>
  1. Test: install the App Store version, create notes, then run the new build over it, and check that the notes are still there and unpinned.
  • Every change = new model version. Lightweight: additive, optional or defaulted, renames via renamingIdentifier. Otherwise staged migration (iOS 17) or mapping models.
  • Migrations run at store load: no fatalError, recovery paths, progress UI for big ones, CI tests from every shipped version.
  • Batch insert/update/delete bypass contexts: merge object IDs (mergeChanges(fromRemoteContextSave:into:)) or use persistent history tracking.
  • Persistent history (+ remote change notifications) for extensions, other processes and CloudKit; purge history.
  • SwiftData coexistence is possible (same store, matching names, history on both) but rarely worth a rewrite.

Check this part

  1. You add a new attribute to an entity. What should it be so lightweight migration just works?

  2. Why is fatalError in loadPersistentStores dangerous?

  3. After an NSBatchDeleteRequest, the list still shows deleted notes. Why?

  4. How does the app learn about writes a widget made to the shared store?

Every model change needs a new model version. Lightweight migration infers simple changes (new optional attributes, renames with a renaming identifier); bigger ones need staged migration (iOS 17) or a mapping model, and must be tested with real old stores, because a failed migration means a crash at launch. Batch requests bypass contexts, so merge their changes; persistent history tracking keeps extensions and batch operations in sync. Move to SwiftData gradually, if at all.

Key takeaways

  • The view context is for the UI on the main queue; background contexts work inside perform.
  • Pass objectIDs between contexts, never the objects.
  • Every model change needs a new model version; keep changes simple and test upgrades.
  • Never crash on a failed store load; recover or explain.
  • Concurrency debug flags turn rare corruption into immediate failures; use them.
  • Merge policies and unique constraints make imports idempotent.
  • Batch operations and other processes need explicit merging or persistent history.
  • Treat migrations as release-critical code with tests from every shipped version; SwiftData is an option, not an obligation.

Finished this page?Nice work, this page is complete!

Mark it as done to track your progress. It's saved in this browser, no account needed.

Its cards are now in your Bites review ⚡
Esc

Type to search the whole site.