美文网首页
【SwiftUI】解决使用SwiftData时Preview报错

【SwiftUI】解决使用SwiftData时Preview报错

作者: ufogxl | 来源:发表于2023-11-08 01:12 被阅读0次
    @Model
    public class SampleData{
        public var content:String?
    }
    
    let container: ModelContainer = {
        try! ModelContainer(
            for: SampleData.self
        )
    }()
    
    struct ContentView: View {
    
        @Query var datas: [SampleData]?
        ///......其他内容
    }
    
    #Preview {
        ContentView()
    }
    

    以上代码在Preview时会抛出异常:failed to find a currently active container for SampleData,但是真机运行没有异常。

    解决方案:

    修改PreView如下:

    #Preview {
        MainActor.assumeIsolated {
            let container = container
            return ContentView()
                   .modelContainer(container)
        }
    }
    

     @MainActor
     let previewContainer: ModelContainer = {
        do {
            let container = try ModelContainer(
                    for: SampleData,
                    configurations: ModelConfiguration(isStoredInMemoryOnly: true)
                )
            let modelContext = container.mainContext
            if try modelContext.fetch(FetchDescriptor< SampleData >()).isEmpty {
                container.mainContext.insert(SampleData(content:"test"))
            }
            return container
        } catch {
            fatalError("Failed to create container")
        }
    }()
    
    #Preview {
        ContentView()
        .modelContainer(previewContainer)
    }
    

    参考:

    https://developer.apple.com/forums/thread/731511

    相关文章

      网友评论

          本文标题:【SwiftUI】解决使用SwiftData时Preview报错

          本文链接:https://www.haomeiwen.com/subject/egtqwdtx.html