Build, review, or improve Core Data persistence in apps that have not adopted SwiftData. Use when working with NSManagedObject subclasses, NSFetchedResultsController for list-driven UI, NSBatchInsertRequest / NSBatchDeleteRequest / NSBatchUpdateRequest for bulk operations, NSPersistentHistoryChangeRequest for persistent history tracking and multi-target sync, NSStagedMigrationManager for staged schema migrations (iOS 17+), NSCompositeAttributeDescription for composite attributes (iOS 17+), or when integrating Core Data threading with Swift Concurrency. For Core Data + SwiftData coexistence or migration, see the swiftdata skill instead.
SKILL.md
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.
NSManagedObjectContext.perform(_:) has an async throws overload
(iOS 15+). Avoid marking NSManagedObject subclasses as Sendable.
func importItems(_ records: [ItemRecord]) async throws {
let context = CoreDataStack.shared.newBackgroundContext()
try await context.perform {
for record in records {
let item = CDItem(context: context)
item.id = record.id
item.title = record.title
}
try context.save()
}
// After save completes, viewContext auto-merges if configured
}
Do not use @unchecked Sendable on managed objects. If you need
cross-boundary communication, pass the objectID (which is Sendable)
and re-fetch:
func deleteOldTrips(before cutoff: Date) async throws {
let context = CoreDataStack.shared.newBackgroundContext()
try await context.perform {
let fetchRequest: NSFetchRequest<NSFetchRequestResult> = CDTrip.fetchRequest()
fetchRequest.predicate = NSPredicate(format: "endDate < %@", cutoff as NSDate)
let request = NSBatchDeleteRequest(fetchRequest: fetchRequest)
request.resultType = .resultTypeObjectIDs
let result = try context.execute(request) as? NSBatchDeleteResult
if let ids = result?.result as? [NSManagedObjectID] {
NSManagedObjectContext.mergeChanges(
fromRemoteContextSave: [NSDeletedObjectsKey: ids],
into: [CoreDataStack.shared.viewContext]
)
}
}
}
NSBatchUpdateRequest (iOS 8+)
func markAllTripsAsNotFavorite() async throws {
let context = CoreDataStack.shared.newBackgroundContext()
try await context.perform {
let request = NSBatchUpdateRequest(entity: CDTrip.entity())
request.propertiesToUpdate = ["isFavorite": false]
request.resultType = .updatedObjectIDsResultType
let result = try context.execute(request) as? NSBatchUpdateResult
if let ids = result?.result as? [NSManagedObjectID] {
NSManagedObjectContext.mergeChanges(
fromRemoteContextSave: [NSUpdatedObjectsKey: ids],
into: [CoreDataStack.shared.viewContext]
)
}
}
}
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:
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 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.
Load staged-migration.md 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.