Skip to content

core-data ​

Core Data stack setup, concurrency patterns, relationship modeling, and migration strategies for existing codebases or apps needing features SwiftData lacks.

When to Use ​

  • Need public CloudKit database (SwiftData is private-only)
  • Need custom migration logic
  • Maintaining existing Core Data codebase
  • Need advanced features not in SwiftData

Key Features ​

Core Data vs SwiftData Decision ​

  • SwiftData – New apps, simpler API, Swift-native
  • Core Data – Features SwiftData lacks (public CloudKit database, custom migration logic), existing codebases

The Golden Rule ​

NEVER pass NSManagedObject across threads. Pass objectID instead.

Modern Stack Setup ​

  • NSPersistentContainer
  • Automatic merge from parent context
  • Background context factory

Concurrency Patterns ​

  • context.perform {} for all context operations
  • newBackgroundContext() for heavy work
  • Async/await support

Quick Reference ​

swift
// Setup
let container = NSPersistentContainer(name: "Model")
container.viewContext.automaticallyMergesChangesFromParent = true

// Background work (CORRECT)
let bgContext = container.newBackgroundContext()
try await bgContext.perform {
    for item in items {
        let entity = Entity(context: bgContext)
        entity.configure(from: item)
    }
    try bgContext.save()
}

// Pass objectID across threads, not the object
let userID = user.objectID
Task.detached {
    let user = bgContext.object(with: userID)
}

Common Anti-Patterns ​

Anti-PatternProblemFix
Singleton contextConcurrency crashesContext per operation
Passing objects across threadsThread-confinement violationPass objectID
Fetching in view bodyRepeated fetchesUse @FetchRequest
No merge policyConflicts crashSet mergePolicy
Simulator-only testingHides migration issuesTest on real device

Migration Checklist ​

MANDATORY before shipping schema changes:

  1. ✓ Test on REAL DEVICE (simulator hides issues)
  2. ✓ Install old version, create data
  3. ✓ Install new version over it
  4. ✓ Verify all data accessible
  5. ✓ Check migration performance
  • core-data-diag – Debugging migrations, thread errors, N+1 queries
  • swiftdata – Modern alternative for new apps
  • database-migration – Safe schema evolution patterns
  • swift-concurrency – Async/await patterns

Resources ​

Released under the MIT License