swiftUI核心数据模型

时间:2020-10-09 10:43:15

标签: core-data swiftui

我创建了一个swiftUI视图并尝试显示核心数据实体,但是预览失败,并且应用程序在运行时崩溃。如何实例化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)
    }
}

enter image description here

1 个答案:

答案 0 :(得分:1)

您应该使用上下文创建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 !!
           }
    }
}