container.mainContext.insert(_:). Call try container.mainContext.save() right after inserting your default records, and only mark your preload flag as completed after save() succeeds. Also replace try! when initializing ModelContainer with proper do/catch error handling so a failed store does not crash your app.Why this happens
When you insert objects into container.mainContext, SwiftData stages those changes in memory first. Although mainContext has autosave enabled by default, autosave runs on run-loop and lifecycle boundaries rather than synchronously at the end of a helper method.
If you set a flag like shouldCreateDefaults = false (often backed by UserDefaults or @AppStorage) immediately after looping over insert(_:), you create a race condition. When the app closes, crashes, or reloads before SwiftData flushes the in-memory changes to SQLite, UserDefaults already remembers that defaults were created, while the database on disk remains empty.
This timing difference often shows up on one physical iPhone while the Simulator and iPad appear to work fine. Differences in backgrounding timing, device storage speed, or an earlier failed launch can leave the store empty permanently once the preload flag is flipped.
A second issue is using try! when creating ModelContainer(for:configurations:). If the SQLite store cannot be opened—for example, due to a schema mismatch during development or a corrupted store file—try! crashes the app immediately without giving you a chance to recover or log the error.
How to fix it
1. Call mainContext.save() right after inserting default data
To guarantee your initial records are persisted before flipping shouldCreateDefaults to false, call try container.mainContext.save() inside a do/catch block and update the flag only if saving succeeds.
import Foundation
import SwiftData
enum CustomContainer {
@MainActor
static func create(shouldCreateDefaults: inout Bool) throws -> ModelContainer {
let schema = Schema([Deal.self])
let configuration = ModelConfiguration()
let container = try ModelContainer(for: schema, configurations: configuration)
if shouldCreateDefaults {
for index in 1...10 {
let deal = Deal(id: index)
container.mainContext.insert(deal)
}
try container.mainContext.save()
shouldCreateDefaults = false
}
return container
}
}
Notice two improvements here:
CustomContaineris anenuminstead of anactor. Becausecreateis marked@MainActorandstatic, anactorwrapper adds no isolation benefit and can cause confusion.shouldCreateDefaults = falseruns aftertry container.mainContext.save()succeeds. Ifsave()throws an error, the flag staystrueso the app can retry on the next launch.
2. Replace try! with error handling and an in-memory fallback
If ModelContainer fails to initialize on a user’s device, crashing with try! gives a poor experience and hides the underlying error. Wrap container creation in do/catch, log the error so you can inspect it in Xcode, and optionally fall back to an in-memory ModelConfiguration so the app still launches.
import SwiftUI
import SwiftData
@main
struct MyApp: App {
@AppStorage("shouldCreateDefaults") private var shouldCreateDefaults = true
private let container: ModelContainer
init() {
var createDefaults = UserDefaults.standard.object(forKey: "shouldCreateDefaults") as? Bool ?? true
do {
let created = try CustomContainer.create(shouldCreateDefaults: &createDefaults)
UserDefaults.standard.set(createDefaults, forKey: "shouldCreateDefaults")
self.container = created
} catch {
print("SwiftData ModelContainer failed: \(error)")
let fallbackConfig = ModelConfiguration(isStoredInMemoryOnly: true)
self.container = try! ModelContainer(for: Deal.self, configurations: fallbackConfig)
}
}
var body: some Scene {
WindowGroup {
ContentView()
}
.modelContainer(container)
}
}
If you see a console error during testing on that physical iPhone, check whether an older build of the app left an incompatible SwiftData store on the device. Deleting the app from the iPhone and reinstalling from Xcode clears the old SQLite files and lets SwiftData build a fresh store.
3. Check whether records already exist instead of relying only on a flag
A UserDefaults boolean can get out of sync with the actual database—for instance, if a user restores a backup or if an earlier build failed midway through setup. A more resilient approach is to query SwiftData with a FetchDescriptor to verify the store is empty before inserting defaults.
import Foundation
import SwiftData
enum CustomContainer {
@MainActor
static func create() throws -> ModelContainer {
let schema = Schema([Deal.self])
let configuration = ModelConfiguration()
let container = try ModelContainer(for: schema, configurations: configuration)
var descriptor = FetchDescriptor<Deal>()
descriptor.fetchLimit = 1
let existingDeals = try container.mainContext.fetch(descriptor)
if existingDeals.isEmpty {
for index in 1...10 {
let deal = Deal(id: index)
container.mainContext.insert(deal)
}
try container.mainContext.save()
}
return container
}
}
Using fetchLimit = 1 keeps the check fast because SwiftData only needs to know whether at least one Deal exists. If the database is empty, it inserts the default items and saves immediately.
How to prevent it
- Always call
save()after bulk preloading: Do not rely onmainContextautosave when seeding initial data during app startup. - Flip setup flags only after
save()succeeds: Never updateUserDefaultsor@AppStoragebefore the database write completes. - Avoid
try!in production startup code: LogModelContainererrors withdo/catchso you can diagnose schema or file-permission issues on real devices. - Prefer database checks over booleans when possible: Checking
fetchLimit = 1ensures your app can still seed data if the store was reset or cleared. - Reinstall the app when testing schema changes on hardware: Old SQLite stores left on a physical iPhone can cause container initialization failures if your
@Modelproperties changed without a migration.
FAQ
Why did SwiftData work on the Simulator and iPad but fail on my iPhone?
Autosave timing varies between devices, and a physical iPhone may also have an older app container or different lifecycle timing than the Simulator. If shouldCreateDefaults was set to false before autosave flushed the inserts to disk, subsequent launches on that iPhone will keep skipping the preload step.
Does mainContext save automatically in SwiftData?
Yes, mainContext has autosaveEnabled turned on by default, which saves periodically on run-loop and lifecycle events. However, when you need data on disk immediately—such as right after seeding default records—you should call try container.mainContext.save() explicitly.
How do I reset a broken SwiftData database on a physical iPhone?
During development, delete the app from the iPhone’s Home Screen and run it again from Xcode. That removes the app’s sandboxed Application Support directory, including the SQLite store files, so SwiftData creates a clean database on the next launch.
Parts of this guide are adapted from content licensed under CC BY-SA 4.0; this article is shared under the same license.
