In my app, previews will crash when isStoredInMemoryOnly is set to false in the main file, but works fine when it's set true. I have tried adding inMemory = true to the Previews and following some of the examples on this site but nothing works.
This is my main file
import SwiftUI
import SwiftData
@main
struct MyApp: App {
var sharedModelContainer: ModelContainer = {
let schema = Schema([
Card.self,
])
// CHANGE INMEMORY TO FALSE
let modelConfiguration = ModelConfiguration(schema: schema, isStoredInMemoryOnly: true)
do {
return try ModelContainer(for: schema, configurations: [modelConfiguration])
} catch {
fatalError("Could not create ModelContainer: \(error)")
}
}()
var body: some Scene {
WindowGroup {
ContentView()
}
.modelContainer(sharedModelContainer)
}
}
Here is ContentView whose Preview crashes:
import SwiftUI
import SwiftData
struct ContentView: View {
@Environment(\.modelContext) private var modelContext
@Query var cards: [Card]
var body: some View {
NavigationStack {
VStack {
// some stuff
.background(Image("Background").brightness(-0.25))
}
.tint(Color(red: 1, green: 1, blue: 0))
.onAppear(perform: {
if UserDefaults.standard.bool(forKey: "notfirst") {
print("not first")
return
}
print("first")
parseInitialData()
UserDefaults.standard.setValue(true, forKey: "notfirst")
})
}
func parseInitialData() {
guard let filename = Bundle.main.path(forResource: "data", ofType: "txt") else {
print("FILE NOT FOUND")
return
}
let contents = try! String(contentsOfFile: filename)
let entries = contents.components(separatedBy: "\n")
var i = 0
for entry in entries {
let sides = entry.components(separatedBy: ":")
if sides.count == 1 { continue }
modelContext.insert(Card(indexInBox: i, level: 1, char: sides[0], solution: sides[1]))
i += 1
}
}
}
#Preview {
ContentView()
.modelContainer(for: Card.self)
}