UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

SwiftData isStoredInMemoryOnly = false causes Preview crash

Forums > SwiftUI

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)
}

   

Hacking with Swift is sponsored by RevenueCat.

SPONSORED Take the pain out of configuring and testing your paywalls. RevenueCat's Paywalls allow you to remotely configure your entire paywall view without any code changes or app updates.

Click to save your free spot now

Sponsor Hacking with Swift and reach the world's largest Swift community!

Reply to this topic…

You need to create an account or log in to reply.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.