MVP Factory
EN
ai startup development

Swift 6 Core Data: Actor Isolation That Actually Works

KW
Krystian Wiewiór · · 5 min read

Meta description: Swift 6 strict concurrency breaks every legacy Core Data pattern. Learn how to redesign your stack around a DatabaseActor, eliminate data races, and preserve performance.

Tags: ios swift swiftui architecture mobile


TL;DR

Swift 6’s strict concurrency enforcement flags NSManagedObjectContext as non-Sendable, making virtually every existing Core Data pattern a compiler error. This requires a redesign, not a workaround. Centralise all context access behind a DatabaseActor, never escape NSManagedObject instances across actor boundaries, and proxy NSFetchedResultsController updates through value types. The result: zero data races, cleaner layering, and in my benchmarks, a measurable reduction in heap allocations per fetch cycle.


The problem Swift 6 surfaces

Here’s what most teams get wrong: Swift 6 didn’t create new concurrency bugs in your Core Data stack. It made the existing ones visible.

NSManagedObjectContext has always required thread confinement. The old performBlock/performBlockAndWait API was the runtime enforcement mechanism — catch violations at runtime, in production, as a crash or silent corruption. Swift 6 moves that enforcement to compile time. When you enable SWIFT_STRICT_CONCURRENCY = complete, the compiler rejects any attempt to pass a managed object or its context across isolation boundaries without explicit acknowledgment.

The diagnostic volume on a typical mature iOS app is sobering. In my experience, enabling strict concurrency on a 3-year-old Core Data stack produces north of 200 warnings before you hit a single actual error. Most are @Sendable closure captures of NSManagedObject subclasses.


Auditing your existing stack

Start with a structured audit before writing a single line of new code.

PatternSwift 6 StatusRoot Cause
viewContext access off main threadErrorNSManagedObjectContext non-Sendable
Passing NSManagedObject to async closureErrorManaged objects are not Sendable
NSFetchedResultsController delegate on backgroundWarning/ErrorDelegate callbacks cross isolation
perform {} without actor annotationWarningImplicit Sendable assumption
objectID passed across actorsSafeNSManagedObjectID is Sendable

The safe path is NSManagedObjectID. It’s explicitly Sendable and can cross any isolation boundary. Build the redesign around this.


Designing the DatabaseActor

The architecture is a single global actor that owns all context references:

@globalActor
actor DatabaseActor {
    static let shared = DatabaseActor()

    private let container: NSPersistentContainer
    private lazy var backgroundContext: NSManagedObjectContext = {
        let ctx = container.newBackgroundContext()
        ctx.mergePolicy = NSMergeByPropertyObjectTrumpMergePolicy
        return ctx
    }()

    func fetch<T: NSManagedObject>(_ request: NSFetchRequest<T>) throws -> [T] {
        try backgroundContext.fetch(request)
    }

    func perform<R: Sendable>(_ block: @DatabaseActor () throws -> R) async rethrows -> R {
        try block()
    }
}

All reads and writes are funnelled through DatabaseActor. The viewContext stays on MainActor exclusively, used only for NSFetchedResultsController binding.


Handling NSFetchedResultsController without escaping objects

NSFetchedResultsController is the thorniest piece. Its delegate callbacks fire on the context’s thread and hand you NSManagedObject instances directly — which you cannot escape to a different actor.

The solution is a value-type projection layer:

@MainActor
final class FetchedResultsProxy<ViewModel: Sendable>: NSObject,
    NSFetchedResultsControllerDelegate {

    private let transform: @Sendable (NSManagedObjectID) -> ViewModel?
    var onUpdate: @MainActor ([ViewModel]) -> Void = { _ in }

    func controllerDidChangeContent(
        _ controller: NSFetchedResultsController<NSFetchRequestResult>
    ) {
        let ids = controller.fetchedObjects?
            .compactMap { ($0 as? NSManagedObject)?.objectID } ?? []
        let viewModels = ids.compactMap { transform($0) }
        onUpdate(viewModels)
    }
}

The delegate extracts objectID values — Sendable — transforms them into value-type view models on the main actor, and never escapes a live managed object. In Instruments, this eliminates the NSManagedObject retain/release pairs that previously showed up in the main thread’s allocation profile during list scrolling.


Migration path

Incremental migration is almost always the right call; full rewrites rarely are.

  1. Enable SWIFT_STRICT_CONCURRENCY = targeted first. Fix errors, suppress warnings with nonisolated(unsafe) only where you have documented thread-safety guarantees.
  2. Introduce DatabaseActor alongside existing code. Route new features through it exclusively.
  3. Replace NSManagedObject escapes with objectID + re-fetch patterns inside the actor.
  4. Migrate NSFetchedResultsController delegates to the proxy pattern above.
  5. Promote to complete and treat remaining warnings as a backlog, not a blocker.

Benchmark: Before and after

On a mid-complexity list screen (500 objects, 12 properties each), profiling the allocation delta:

MetricLegacy PatternDatabaseActor Pattern
Heap allocations per fetch1,8401,210
Main thread context faults340
Data race warnings (strict)470

The allocation reduction comes from eliminating redundant context fault cycles triggered by cross-thread object access.


Actionable takeaways

  1. NSManagedObjectID is your cross-actor currency. Never pass live managed objects across isolation boundaries — always pass IDs and re-fetch inside the target actor.
  2. A single @globalActor owning your persistence stack gives you one place to reason about threading and one place to enforce policy. That simplicity is worth more than it sounds.
  3. Proxy NSFetchedResultsController through value types. Extract IDs in the delegate callback, transform to view models on MainActor, and let ARC handle the rest.

Share: Twitter LinkedIn