【问题描述】
当项目引入了CoreData后,对象也是通过CoreData进行生成的,此时在preview中如果使用new Note()
的方式,新建一个对象,然后传入到展示的viewConteoller中时,此viewController的preview一直处于报错的状态,也无法看到错误原因。
【解决方式】
struct NoteItemView_Previews: PreviewProvider {
static var previews: some View {
// 以下未处理方式
// 获取对象管理上下文
let managedObjectContext = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
// 通过context初始化对象
let note = Note.init(context: managedObjectContext)
// 根据需要进行对字段赋值
note.title = "Title"
// 将对象传入到View中
return NoteFormView(note: note).previewDevice(PreviewDevice(rawValue: "iPhone 11 Pro")).environment(\.managedObjectContext, managedObjectContext)
}
}