iOS Core Data Architect
Expert in Core Data persistence, CloudKit synchronization, schema migrations, and migration paths to SwiftData.
Activation Triggers
Activate on: "Core Data", "NSManagedObject", "CloudKit sync", "Core Data migration", "NSFetchedResultsController", "NSPersistentContainer", "SwiftData migration", "lightweight migration", "Core Data performance"
NOT for: SwiftUI state management → swiftui-data-flow-expert | Server databases → data-pipeline-engineer | SQLite direct → mobile-offline-sync-architect
Quick Start
- Assess project state — new project? Use SwiftData. Existing Core Data? Evaluate migration vs coexistence.
- Design data model — entities, relationships, fetch indexes in the .xcdatamodeld editor
- Configure persistent container — NSPersistentCloudKitContainer for CloudKit sync, NSPersistentContainer for local-only
- Implement migration plan — lightweight (automatic) or heavyweight (mapping model) depending on schema changes
- Optimize fetching — batch size, prefetching, background contexts for heavy operations
Core Capabilities
| Domain |
Technologies |
| Persistence |
NSPersistentContainer, NSManagedObjectContext, WAL mode |
| CloudKit |
NSPersistentCloudKitContainer, CKRecord zone, conflict resolution |
| Migrations |
Lightweight migration, mapping models, progressive migration |
| Performance |
NSBatchInsertRequest, NSBatchDeleteRequest, faulting, prefetch |
| SwiftData |
Coexistence with Core Data, migration path, @Model from NSManagedObject |
Architecture Patterns
Core Data Stack Setup with CloudKit
class PersistenceController {
static let shared = PersistenceController()
let container: NSPersistentCloudKitContainer
init(inMemory: Bool = false) {
container = NSPersistentCloudKitContainer(name: "MyApp")
guard let description = container.persistentStoreDescriptions.first else {
fatalError("No store description")
}
if inMemory {
description.url = URL(fileURLWithPath: "/dev/null")
}
// CloudKit configuration
description.cloudKitContainerOptions = NSPersistentCloudKitContainerOptions(
containerIdentifier: "iCloud.com.example.myapp"
)
// Enable remote change notifications
description.setOption(true as NSNumber,
forKey: NSPersistentStoreRemoteChangeNotificationPostOptionKey)
// Enable persistent history tracking
description.setOption(true as NSNumber,
forKey: NSPersistentHistoryTrackingKey)
container.loadPersistentStores { _, error in
if let error { fatalError("Store failed: \(error)") }
}
container.viewContext.automaticallyMergesChangesFromParent = true
container.viewContext.mergePolicy = NSMergeByPropertyObjectTrumpMergePolicy
}
// Background context for heavy operations
func newBackgroundContext() -> NSManagedObjectContext {
let context = container.newBackgroundContext()
context.mergePolicy = NSMergeByPropertyObjectTrumpMergePolicy
return context
}
}
Progressive Migration Strategy
Version 1 → Version 2 (add optional column):
└─ Lightweight migration (automatic)
Version 2 → Version 3 (rename attribute):
└─ Mapping model required (heavyweight)
Version 3 → Version 4 (split entity):
└─ Custom migration with NSEntityMigrationPolicy
Strategy: Progressive migration chain
v1 → v2 → v3 → v4 (each step is a known migration)
NOT: v1 → v4 directly (complex, error-prone)
Code:
for migration in migrationChain {
try coordinator.addPersistentStore(
ofType: NSSQLiteStoreType,
configurationName: nil,
at: storeURL,
options: [NSMigratePersistentStoresAutomaticallyOption: true,
NSInferMappingModelAutomaticallyOption: migration.isLightweight]
)
}
SwiftData Coexistence (Migration Path)
// Phase 1: Core Data and SwiftData side-by-side
// Share the same SQLite store file
let schema = Schema([NewEntity.self]) // SwiftData models
let config = ModelConfiguration(
url: existingCoreDataStoreURL // Same store as Core Data
)
let container = try ModelContainer(for: schema, configurations: [config])
// Phase 2: Gradually move entities from Core Data to SwiftData
// - New entities: @Model (SwiftData)
// - Existing entities: NSManagedObject (Core Data)
// - Read from both, write to SwiftData for new data
// Phase 3: Full migration
// - Convert all NSManagedObject subclasses to @Model
// - Remove .xcdatamodeld file
// - Use ModelContainer exclusively
Anti-Patterns
- Using viewContext for writes — viewContext is on the main thread; heavy writes block the UI. Use
performBackgroundTask or newBackgroundContext() for inserts and batch operations.
- No batch operations for bulk data — inserting 10K records one-by-one creates 10K change notifications. Use
NSBatchInsertRequest which bypasses the context and writes directly.
- Ignoring faulting — accessing all properties of all objects in a list. Core Data uses faulting to lazy-load; respect it by only accessing displayed properties. Set
fetchBatchSize.
- Heavyweight migration without testing — mapping models are complex and fail silently with data corruption. Test every migration path against real production data copies.
- Skipping persistent history tracking — required for CloudKit sync and multi-process coordination (widgets, extensions). Always enable
NSPersistentHistoryTrackingKey.
Quality Checklist
[ ] Persistent container configured correctly (CloudKit or local)
[ ] viewContext used only for reads; background context for writes
[ ] NSBatchInsertRequest used for bulk operations
[ ] Fetch requests have fetchBatchSize set (typically 20-50)
[ ] Migration plan documented for each model version
[ ] Lightweight migration tested between all adjacent versions
[ ] CloudKit sync tested (if applicable) with conflict resolution
[ ] Persistent history tracking enabled
[ ] NSFetchedResultsController used for table/list data sources
[ ] Background context mergePolicy set explicitly
[ ] Unit tests use in-memory store for speed
[ ] SwiftData migration path documented for future transition
1---
2license: Apache-2.0
3name: ios-core-data-architect
4description: "iOS Core Data architect for persistent storage, CloudKit sync, schema migrations, and SwiftData migration. Activate on: Core Data, NSManagedObject, CloudKit sync, Core Data migration, NSFetchedResultsController, NSPersistentContainer, SwiftData migration path. NOT for: SwiftUI state management (use swiftui-data-flow-expert), server databases (use data-pipeline-engineer), SQLite direct (use mobile-offline-sync-architect)."
5allowed-tools: Read,Write,Edit,Bash(swift:*,xcodebuild:*)
6category: Mobile Development
7tags:
8 - core-data
9 - ios
10 - cloudkit
11 - persistence
12pairs-with:
13 - skill: swiftui-data-flow-expert
14 reason: SwiftUI views consume Core Data/SwiftData models
15 - skill: mobile-offline-sync-architect
16 reason: Core Data + CloudKit is an offline sync solution
17metadata:
18 source: https://skillmd.com/skills/curiositech/ios-core-data-architect
19---
20
21# iOS Core Data Architect
22
23Expert in Core Data persistence, CloudKit synchronization, schema migrations, and migration paths to SwiftData.
24
25## Activation Triggers
26
27**Activate on:** "Core Data", "NSManagedObject", "CloudKit sync", "Core Data migration", "NSFetchedResultsController", "NSPersistentContainer", "SwiftData migration", "lightweight migration", "Core Data performance"
28
29**NOT for:** SwiftUI state management → `swiftui-data-flow-expert` | Server databases → `data-pipeline-engineer` | SQLite direct → `mobile-offline-sync-architect`
30
31## Quick Start
32
331. **Assess project state** — new project? Use SwiftData. Existing Core Data? Evaluate migration vs coexistence.
342. **Design data model** — entities, relationships, fetch indexes in the .xcdatamodeld editor
353. **Configure persistent container** — NSPersistentCloudKitContainer for CloudKit sync, NSPersistentContainer for local-only
364. **Implement migration plan** — lightweight (automatic) or heavyweight (mapping model) depending on schema changes
375. **Optimize fetching** — batch size, prefetching, background contexts for heavy operations
38
39## Core Capabilities
40
41| Domain | Technologies |
42|--------|-------------|
43| **Persistence** | NSPersistentContainer, NSManagedObjectContext, WAL mode |
44| **CloudKit** | NSPersistentCloudKitContainer, CKRecord zone, conflict resolution |
45| **Migrations** | Lightweight migration, mapping models, progressive migration |
46| **Performance** | NSBatchInsertRequest, NSBatchDeleteRequest, faulting, prefetch |
47| **SwiftData** | Coexistence with Core Data, migration path, @Model from NSManagedObject |
48
49## Architecture Patterns
50
51### Core Data Stack Setup with CloudKit
52
53```swift
54class PersistenceController {
55 static let shared = PersistenceController()
56
57 let container: NSPersistentCloudKitContainer
58
59 init(inMemory: Bool = false) {
60 container = NSPersistentCloudKitContainer(name: "MyApp")
61
62 guard let description = container.persistentStoreDescriptions.first else {
63 fatalError("No store description")
64 }
65
66 if inMemory {
67 description.url = URL(fileURLWithPath: "/dev/null")
68 }
69
70 // CloudKit configuration
71 description.cloudKitContainerOptions = NSPersistentCloudKitContainerOptions(
72 containerIdentifier: "iCloud.com.example.myapp"
73 )
74
75 // Enable remote change notifications
76 description.setOption(true as NSNumber,
77 forKey: NSPersistentStoreRemoteChangeNotificationPostOptionKey)
78
79 // Enable persistent history tracking
80 description.setOption(true as NSNumber,
81 forKey: NSPersistentHistoryTrackingKey)
82
83 container.loadPersistentStores { _, error in
84 if let error { fatalError("Store failed: \(error)") }
85 }
86
87 container.viewContext.automaticallyMergesChangesFromParent = true
88 container.viewContext.mergePolicy = NSMergeByPropertyObjectTrumpMergePolicy
89 }
90
91 // Background context for heavy operations
92 func newBackgroundContext() -> NSManagedObjectContext {
93 let context = container.newBackgroundContext()
94 context.mergePolicy = NSMergeByPropertyObjectTrumpMergePolicy
95 return context
96 }
97}
98```
99
100### Progressive Migration Strategy
101
102```
103Version 1 → Version 2 (add optional column):
104 └─ Lightweight migration (automatic)
105
106Version 2 → Version 3 (rename attribute):
107 └─ Mapping model required (heavyweight)
108
109Version 3 → Version 4 (split entity):
110 └─ Custom migration with NSEntityMigrationPolicy
111
112Strategy: Progressive migration chain
113 v1 → v2 → v3 → v4 (each step is a known migration)
114 NOT: v1 → v4 directly (complex, error-prone)
115
116Code:
117 for migration in migrationChain {
118 try coordinator.addPersistentStore(
119 ofType: NSSQLiteStoreType,
120 configurationName: nil,
121 at: storeURL,
122 options: [NSMigratePersistentStoresAutomaticallyOption: true,
123 NSInferMappingModelAutomaticallyOption: migration.isLightweight]
124 )
125 }
126```
127
128### SwiftData Coexistence (Migration Path)
129
130```swift
131// Phase 1: Core Data and SwiftData side-by-side
132// Share the same SQLite store file
133let schema = Schema([NewEntity.self]) // SwiftData models
134let config = ModelConfiguration(
135 url: existingCoreDataStoreURL // Same store as Core Data
136)
137let container = try ModelContainer(for: schema, configurations: [config])
138
139// Phase 2: Gradually move entities from Core Data to SwiftData
140// - New entities: @Model (SwiftData)
141// - Existing entities: NSManagedObject (Core Data)
142// - Read from both, write to SwiftData for new data
143
144// Phase 3: Full migration
145// - Convert all NSManagedObject subclasses to @Model
146// - Remove .xcdatamodeld file
147// - Use ModelContainer exclusively
148```
149
150## Anti-Patterns
151
1521. **Using viewContext for writes** — viewContext is on the main thread; heavy writes block the UI. Use `performBackgroundTask` or `newBackgroundContext()` for inserts and batch operations.
1532. **No batch operations for bulk data** — inserting 10K records one-by-one creates 10K change notifications. Use `NSBatchInsertRequest` which bypasses the context and writes directly.
1543. **Ignoring faulting** — accessing all properties of all objects in a list. Core Data uses faulting to lazy-load; respect it by only accessing displayed properties. Set `fetchBatchSize`.
1554. **Heavyweight migration without testing** — mapping models are complex and fail silently with data corruption. Test every migration path against real production data copies.
1565. **Skipping persistent history tracking** — required for CloudKit sync and multi-process coordination (widgets, extensions). Always enable `NSPersistentHistoryTrackingKey`.
157
158## Quality Checklist
159
160```
161[ ] Persistent container configured correctly (CloudKit or local)
162[ ] viewContext used only for reads; background context for writes
163[ ] NSBatchInsertRequest used for bulk operations
164[ ] Fetch requests have fetchBatchSize set (typically 20-50)
165[ ] Migration plan documented for each model version
166[ ] Lightweight migration tested between all adjacent versions
167[ ] CloudKit sync tested (if applicable) with conflict resolution
168[ ] Persistent history tracking enabled
169[ ] NSFetchedResultsController used for table/list data sources
170[ ] Background context mergePolicy set explicitly
171[ ] Unit tests use in-memory store for speed
172[ ] SwiftData migration path documented for future transition
173```