Core Data
Build and maintain data persistence using Core Data for apps that have not adopted SwiftData. Covers stack setup, concurrency, batch operations, NSFetchedResultsController, persistent history tracking, staged migration, and testing.
Contents
- Stack Setup
- Concurrency and Threading
- NSFetchedResultsController
- Batch Operations
- Persistent History Tracking
- Staged Migration
- Composite Attributes
- SwiftData Boundary
- Testing
- Common Mistakes
- Review Checklist
- References
Stack Setup
NSPersistentContainer encapsulates the Core Data stack.
Docs: NSPersistentContainer
For CloudKit sync, use NSPersistentCloudKitContainer instead.
Concurrency and Threading
Core Data contexts are bound to queues. The viewContext is on the main queue;
background contexts operate on private queues.
Docs: NSManagedObjectContext
Rules:
- Always use
perform(_:)orperformAndWait(_:)when accessing a context off its own queue. - Never pass
NSManagedObjectinstances across context or thread boundaries. PassNSManagedObjectIDinstead and re-fetch. - Set
automaticallyMergesChangesFromParent = trueon theviewContext.
Swift Concurrency Integration
NSManagedObjectContext.perform(_:) has an async throws overload
(iOS 15+). Avoid marking NSManagedObject subclasses as Sendable.
Do not use @unchecked Sendable on managed objects. If you need
cross-boundary communication, pass the objectID (which is Sendable)
and re-fetch:
NSFetchedResultsController
Efficiently drives UITableView / UICollectionView from a Core Data fetch
request, with built-in change tracking and optional caching.
Docs: NSFetchedResultsController
Key points:
- The fetch request must have at least one sort descriptor.
- Call
deleteCache(withName:)before changing the fetch request predicate or sort descriptors, or setcacheNametonil. - The diffable snapshot delegate method (
didChangeContentWith:) is available iOS 13+ and is preferred over the older per-change callbacks. - After a context
reset(), callperformFetch()again.
Batch Operations
Batch operations execute at the SQL level, bypassing the managed object context. They are fast but don't trigger context notifications automatically.
NSBatchInsertRequest (iOS 13+)
Docs: NSBatchInsertRequest
NSBatchDeleteRequest (iOS 9+)
Docs: NSBatchDeleteRequest
NSBatchUpdateRequest (iOS 8+)
Always merge changes back into relevant contexts after batch operations. Batch delete does not enforce the Deny delete rule.
For destructive or retryable batch work, use a proof loop: preflight the predicate and expected count, execute with an object-ID result type, merge IDs into live contexts, refetch, and assert the postcondition. On failure, restore a pristine fixture or prove the operation is idempotent before retrying; never blindly rerun a partially completed batch.
Persistent History Tracking
Track store-level changes across targets (app, extensions, widgets) and processes. The core workflow is:
Docs: NSPersistentHistoryChangeRequest
- Enable persistent history and remote-change notifications before loading the store.
- Observe changes and fetch transactions after the target's durable token.
- Merge transaction notifications into live contexts, then persist the new token.
- Purge only history that every relevant consumer has processed.
Load persistent-history.md [blocked] when implementing the store options, observer, token persistence, merge loop, or purge policy.
Staged Migration
NSStagedMigrationManager (iOS 17+) sequences schema migrations through
ordered lightweight or custom stages. Stage inputs use compiled model-version
checksums, not model names. Apps supporting systems below iOS 17 need the
lightweight migration or mapping-model path.
Docs: NSStagedMigrationManager
Load staged-migration.md [blocked] when building the ordered stages, model references, custom handler, and persistent-store option.
Composite Attributes
iOS 17+ supports composite attributes: groups of sub-attributes on an entity that act as a single logical unit. Define them in the model editor by adding a Composite type attribute and nesting sub-attributes beneath it.
Docs: NSCompositeAttributeDescription
Composite attributes map to Codable structs in SwiftData coexistence
scenarios.
SwiftData Boundary
Use the swiftdata skill for Core Data + SwiftData coexistence or migration
implementation. Before handing off, preserve these Core Data boundaries:
- SwiftData must point at the existing persistent store URL when it is meant to share or migrate Core Data data.
- Shared persisted data must keep entity names, property names, types, and
schema compatible across the Core Data model and SwiftData
@Modelclasses. - Map renamed persisted properties with SwiftData
@Attribute(originalName:).
Testing
In-Memory Store for Tests
Tips:
- Share the
NSManagedObjectModelinstance across tests to avoid "duplicate entity" warnings. - Use a single shared model loaded once:
Common Mistakes
Review Checklist
-
NSPersistentContaineris initialized once and shared -
viewContextused only on main queue; background contexts for writes -
perform(_:)orperformAndWait(_:)wraps all off-queue context access -
automaticallyMergesChangesFromParentset onviewContext -
mergePolicyset onviewContextto prevent conflict crashes - Batch operation results merged into relevant contexts
-
NSFetchedResultsControllerfetch requests have sort descriptors - Persistent history tracking enabled for multi-target apps
- Core Data + SwiftData handoff preserves store URL, schema compatibility, entity/property names, and rename mappings
- Tests use in-memory stores with shared
NSManagedObjectModel - No
NSManagedObjectinstances cross thread boundaries
References
- Persistent history across targets and processes [blocked]
- Staged lightweight and custom migration [blocked]
- Apple docs: Core Data | NSPersistentContainer | NSFetchedResultsController | NSStagedMigrationManager


