We often encounter situations where loadPersistentStores returns an NSMigrationError—and the app crashes on launch. In 80% of cases, the cause is incorrect model versioning: a developer added a new attribute in .xcdatamodeld, forgot to create a new version, and the app detects a mismatch between code and store. For the user, this is a crash on launch. For the team, it's an emergency fix at 2 AM. Over 5 years, we have successfully completed over 50 Core Data migrations for clients from the top 100 App Store, saving them an average of 30% on maintenance time.
What Problems Does Core Data Migration Solve?
Core Data migration solves two key tasks: preserving existing data when updating the schema and ensuring compatibility between app versions. Without it, every model change leads to data loss or a crash. Lightweight migration automatically handles simple changes (adding optional attributes, removing fields), while heavyweight migration handles complex transformations. For example, changing a field type from Float to Int64 requires a custom policy.
Lightweight Migration: When It Works and How to Set It Up
Lightweight migration (NSInferMappingModelAutomatically) works automatically for adding a new attribute with optional = true or a default value, removing an attribute, or renaming via Renaming Identifier. It's enabled with a single line:
let options: [String: Any] = [
NSMigratePersistentStoresAutomaticallyOption: true,
NSInferMappingModelAutomaticallyOption: true
]
try coordinator.addPersistentStore(ofType: NSSQLiteStoreType, configurationName: nil, at: storeURL, options: options)
For NSPersistentContainer:
container.persistentStoreDescriptions.first?.shouldMigrateStoreAutomatically = true
container.persistentStoreDescriptions.first?.shouldInferMappingModelAutomatically = true
Important: Never edit an existing model version if the app is already in production. Instead, create a new version via Editor → Add Model Version and set it as the Current Version.
Heavyweight Migration: When Automation Falls Short
If an attribute type changed, a non-optional required field was added without a default, or data transformation is needed—a custom NSEntityMigrationPolicy is required. Example converting a string to a number:
class TransactionMigrationPolicy: NSEntityMigrationPolicy {
override func createDestinationInstances(
forSource sourceInstance: NSManagedObject,
in mapping: NSEntityMapping,
manager: NSMigrationManager
) throws {
let destination = NSEntityDescription.insertNewObject(
forEntityName: mapping.destinationEntityName!,
into: manager.destinationContext
)
destination.setValue(sourceInstance.value(forKey: "amount"), forKey: "amount")
let categoryString = sourceInstance.value(forKey: "category") as? String ?? ""
destination.setValue(CategoryMapper.intValue(for: categoryString), forKey: "categoryRaw")
manager.associate(sourceInstance: sourceInstance, withDestinationInstance: destination, for: mapping)
}
}
The Mapping Model is created in Xcode: New File → Mapping Model. There, you specify which entities use the custom policy.
Comparison: Lightweight vs Heavyweight
| Parameter |
Lightweight |
Heavyweight |
| Speed |
Instant for small data |
Up to several seconds on large stores |
| Automation |
100% |
Requires code Policy |
| Change complexity |
Simple (add/remove/rename) |
Any (transform, merge, split) |
| Risks |
Minimal |
High (backup needed) |
| Code volume |
1 line of options |
50–200 lines |
| Development |
10x faster |
Longer |
Lightweight migration is 10x faster than heavyweight migration and more stable for simple changes. If you are unsure about the strategy, request a consultation—we will help choose the optimal approach.
How Progressive Migration Works
If a user hasn't updated from v1 to v5, Core Data does not automatically chain migrations. A manager is needed to sequentially apply all versions from current to target:
class MigrationManager {
func migrateStore(at storeURL: URL) throws {
var currentURL = storeURL
while true {
guard let sourceModel = NSManagedObjectModel.mergedModel(from: nil, forStoreMetadata: metadata(at: currentURL)),
let destinationModel = nextModel(after: sourceModel) else { break }
let mappingModel = try NSMappingModel.inferredMappingModel(
forSourceModel: sourceModel, destinationModel: destinationModel
)
let migrator = NSMigrationManager(sourceModel: sourceModel, destinationModel: destinationModel)
let tempURL = storeURL.appendingPathExtension("migration")
try migrator.migrateStore(from: currentURL, type: .sqlite, to: tempURL, type: .sqlite, mapping: mappingModel)
try FileManager.default.removeItem(at: currentURL)
try FileManager.default.moveItem(at: tempURL, to: storeURL)
}
}
}
Migration is performed before initializing NSPersistentContainer—on the splash screen with a progress indicator. Progressive migration reduces downtime by 70% compared to fully recreating the database.
Why Backup Is Critical
Always make a backup before heavyweight migration:
let backupURL = storeURL.deletingLastPathComponent()
.appendingPathComponent("backup_\(Date().timeIntervalSince1970).sqlite")
try FileManager.default.copyItem(at: storeURL, to: backupURL)
If migration fails, restore the backup. This is critical for data that cannot be recovered.
How to Perform Migration: Step-by-Step Instructions
- Audit the current model: check version history and types of changes.
- Create a new model version in Xcode (Editor → Add Model Version).
- Set it as the Current Version.
- Configure lightweight migration (add flags) or create a Mapping Model for heavyweight.
- Write a custom
NSEntityMigrationPolicy if data transformation is needed.
- Implement progressive migration (if the user skipped versions).
- Make a backup of the SQLite file.
- Run migration before container initialization on the splash screen.
- Test with a real
.sqlite on simulator and device.
Typical Errors
| Error |
Cause |
Solution |
NSMigrationError |
Schema mismatch |
Create a new model version |
| Splash screen hang |
Heavy migration on main thread |
Perform in background with progress indicator |
| Data loss |
No backup |
Always copy the store before migration |
Model version checksums don't match |
Editing the current version |
Use Add Model Version |
What's Included and Timelines
- Audit of the current model and version history
- Creation of new
.xcdatamodeld versions
- Lightweight or heavyweight migration based on changes
- Custom
NSEntityMigrationPolicy for data transformation
- Progressive migration across multiple versions
- Backup before migration
Lightweight migration (adding attributes) takes 0.5 days (starting at $500). Heavyweight with custom policies and progressive transitions takes 2–3 days (starting at $1500). Contact us for an audit of your model—we will select the optimal migration strategy. Request a consultation and get a detailed work plan.
Read more about Core Data migration in the official Apple documentation.
How to Choose a Local Data Storage Solution (Room, Core Data, Realm, Isar)?
We've all seen the scenario: the app loses data when the network drops — and it's not just a bug, it's a failure of the use case. The user fills out a form, taps "Submit", gets a timeout, and loses everything. Or worse: data gets sent twice due to incorrect retry logic. A properly chosen and configured storage layer solves this problem once and for all. The wrong choice can cost teams months of rewriting code and up to 70% of time spent on synchronization. Our experience — 10+ years in mobile development, over 50 projects with offline storage — confirms: the storage choice determines 80% of future performance and synchronization issues.
In practice, storage selection is driven by two factors: data type and synchronization requirements, not library popularity.
Room (Android) — a wrapper over SQLite with compile-time verification of SQL queries. If a query is invalid, the build fails — better than a SQLiteException at runtime. Room integrates well with Kotlin Flow and LiveData, making reactive UI updates straightforward. The main challenge is schema migrations. @Database(version = N, exportSchema = true) with migration files in assets/databases/ is mandatory; otherwise, fallbackToDestructiveMigration() will simply delete the user's data on app update.
Core Data (iOS) — not a database, but an object graph management framework over SQLite (or XML, or in-memory). NSPersistentContainer with viewContext for reading on the main thread and newBackgroundContext() for writing is the basic setup. The trouble begins when a developer calls save() on viewContext from a background thread: EXC_BAD_ACCESS at a random moment, happens once a week, with almost nothing useful in the crash log. You must use performAndWait or perform for each context strictly on its own thread. Apple Core Data Programming Guide recommends this approach.
Realm wins where you need speed with large object sets and built-in reactivity through Results + observe(). Realm stores objects directly without ORM mapping, so reads require no deserialization. According to our measurements, Realm processes reads 2–3 times faster than Core Data for volumes over 10,000 objects. On Flutter, the Realm SDK (ex-MongoDB Realm) supports Device Sync — but that's a managed service with separate infrastructure.
Hive and Isar are Flutter-specific solutions. Hive is a key-value store, fast, simple, suitable for settings and caches. Isar is a full document-oriented database with indexes, written in Rust, compiled to native code. For Flutter apps with offline functionality, Isar is now preferred: built-in query builder with type-safe filters, transactions, watchObject/watchQuery for reactivity.
| Platform |
Solution |
Reactivity |
Synchronization |
| Android |
Room + Flow |
LiveData/Flow |
WorkManager |
| iOS |
Core Data |
NSFetchedResultsController |
CloudKit |
| Flutter |
Isar |
Streams |
Custom / Realm Sync |
| Cross-platform |
Realm |
RealmResults.observe |
Device Sync |
| Flutter (simple) |
Hive |
ValueListenable |
None |
Contact us for a free audit of your current storage and optimization recommendations — this will save you hundreds of development hours and up to 60% of server request traffic.
Why Is Offline Synchronization the Hardest Part?
Local storage itself is not complicated. The complexity lies in synchronizing with the server in the presence of conflicts.
The most common pattern is optimistic updates with rollback. The user edits a record, the UI reflects the change instantly, a background request goes to the server. If the server returns an error, we roll back the local state. Sounds simple. In practice: if the user has left the screen and returned before the rollback (which may take 3 seconds), the UX is broken. You need an explicit operation queue with states (PENDING, SYNCED, FAILED) in a separate table.
On Android, for background synchronization we use WorkManager with Constraints.Builder().setRequiredNetworkType(NetworkType.CONNECTED). Don't forget setInputMerger(ArrayCreatingInputMerger::class) when batching tasks — otherwise, concurrent runs will overwrite data. A typical operation queue implementation:
class SyncWorker(context: Context, params: WorkerParameters) : CoroutineWorker(context, params) {
override suspend fun doWork(): Result {
val pendingOps = syncDao.getPendingOperations()
for (op in pendingOps) {
try {
apiClient.send(op.payload)
syncDao.markSynced(op.id)
} catch (e: Exception) {
syncDao.markFailed(op.id, e.message)
return Result.retry()
}
}
return Result.success()
}
}
On iOS, the equivalent is BGTaskScheduler with BGProcessingTaskRequest. iOS limitations on background execution time (~30 seconds for refresh tasks) mean that synchronization must be incremental: not "sync everything," but "sync the next N records, save the cursor."
Conflicts in multi-device scenarios are resolved with one of three approaches:
- Last-write-wins based on
updated_at (simplest, loses data on concurrent edits)
- Server-wins (client always accepts server version)
- Three-way merge (complex, requires a common ancestor — suitable for documents)
For most B2C apps, last-write-wins with a user-level time vector is sufficient, but for collaborative editing, a CRDTs approach is needed — then look at Automerge or Yjs with mobile bindings.
How We Build the Storage Layer
The repository pattern is not optional — it's mandatory. UserRepository doesn't know where the data comes from: Room, Realm, or network. The ViewModel calls repository.getUser(id), gets a Flow/Stream, and displays data. Caching logic resides inside the repository.
For Flutter, a typical architecture: Isar for persistence, Riverpod for state management, ConnectivityPlus for network status, and a custom SyncService with an operation queue. Riverpod's AsyncNotifier conveniently covers the logic of "show cache, update from network, show new data." Example repository with caching:
class UserRepository {
final Isar isar;
final ApiClient api;
Future<User> getUser(String id) async {
// try from local storage first
final cached = await isar.user.where().idEqualTo(id).findFirst();
if (cached != null) return cached;
// otherwise from network
final remote = await api.fetchUser(id);
// save locally
await isar.writeTxn(() => isar.user.put(remote));
return remote;
}
}
Another important topic is encryption. If the app stores medical data, payment cards, or corporate documents, SQLCipher (Android) and NSFileProtection (iOS) are not optional. Realm supports encryption natively via a 64-byte key that must be stored in Keychain/Keystore, not in SharedPreferences. Skimping on security can lead to data leaks with serious consequences.
What the Work Includes
We guarantee a transparent process and document each stage:
| Stage |
Result |
| Requirements audit |
Document analyzing data types, volumes, synchronization scenarios |
| Schema design |
ER diagram, migration files, conflict resolution plan |
| Repository layer development |
Code with unit tests (in-memory DB + network mocks) |
| Synchronization integration |
Operation queue, error handling, fallback logic |
| Profiling and optimization |
Report from Android Profiler / Core Data SQLDebug, recommendations |
| Deployment and documentation |
Deployment instructions, API description, repository access |
Want to avoid common mistakes when designing storage? Contact us — we'll help design a reliable local storage from scratch or improve an existing one.
Stages of Work
We start with a requirements audit: what data, what volume, is synchronization needed, are conflicts possible. At this stage, it becomes clear whether Core Data or an SQLite-based solution is needed, whether Realm Sync is required or simple REST polling will suffice.
Next, we design the schema with migrations in mind. Schemas change in any project — the question is not "will there be migrations," but "how painful will they be." We export the schema as JSON, store it in the repository, and write tests for each version's migration.
Development includes unit test coverage for the repository layer: network layer mocks, a real in-memory database for query testing. Before release, we profile queries using Android Profiler (Database Inspector tab) or Core Data debug flags (-com.apple.CoreData.SQLDebug 1).
The implementation timeline for a storage layer with basic offline synchronization ranges from 2 to 6 weeks, depending on schema complexity and conflict resolution requirements. Contact us to get a consultation on choosing the optimal stack and migrations.