为什么我的 Xcode 预览使用 SwiftData 会崩溃

问题描述 投票:0回答:1

我不明白为什么我的问题很接近,我尝试重新发布它。

正如我之前提到的,我没有打印输出或错误消息,只是我的预览崩溃了。

看我的照片:

我尝试简化我的代码以便可重现。

我不明白为什么如果我在配置上设置 isStoredInMemoryOnly: false 预览会崩溃。

import SwiftUI
import SwiftData

@main
struct Cost_ControlApp: App {
   
    var sharedModelContainer: ModelContainer = {

        do {
            let  schema = Schema([Account.self,
                                  Movement.self,
                                  Category.self])
            
            //if i put false my preview crash -----------------------
            let config = ModelConfiguration(isStoredInMemoryOnly: false)
            return try ModelContainer(for: schema, configurations: config)
        } catch {
            fatalError("Could not create ModelContainer: \(error)")
        }
    }()

    var body: some Scene {
        WindowGroup {
            ContentView()
        }
        .modelContainer(sharedModelContainer)
    }
}



struct ContentView: View {
    @Environment(\.modelContext) private var modelContext
    
    
    var body: some View {
        
        Text("Hello")
                
    }
}

#Preview {
    ContentView()
        .modelContainer(for: [Account.self,Movement.self, Category.self], inMemory: true)
}

一旦我在配置上设置 isStoredInMemoryOnly: true,预览就会恢复工作,不会再出现代码崩溃。

但是如果我构建应用程序,它就可以完美运行,没有问题。

xcode swiftui preview swift-data
1个回答
0
投票

当预览需要内存数据时,您尝试呈现持久数据。尝试按照本教程进行操作:https://www.hackingwithswift.com/quick-start/swiftdata/how-to-use-swiftdata-in-swiftui-previews

© www.soinside.com 2019 - 2024. All rights reserved.