@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)
}
参考: