我创建了一个 swiftUI View 并尝试显示核心数据实体,但预览失败并且应用程序在运行时崩溃。如何实例化一个 Movie
对象并将其用作 swiftUI 中的状态成员?
import SwiftUI
struct SwiftUIView: View {
@Environment(\.managedObjectContext) private var viewContext
@State private var movie: Movie = Movie()
var body: some View {
Text(movie.title ?? "empty")
}
}
struct SwiftUIView_Previews: PreviewProvider {
static var previews: some View {
let moc = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
SwiftUIView().environment(\.managedObjectContext, moc)
}
}
最佳答案
您应该使用上下文创建 CoreData 对象,因此这是可能的方法
struct SwiftUIView: View {
@Environment(\.managedObjectContext) private var viewContext
@State private var movie: Movie?
var body: some View {
Text(movie.title ?? "empty")
.onAppear {
self.movie = Movie(context: viewContext) // << here !!
}
}
}
关于core-data - swiftUI核心数据模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64278454/