本文介绍了SwiftUI预览画布和核心数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
预览画布崩溃了,但是在模拟器中一切正常。我假设它与@ObservedObject和@Fetchrequest有关...
Preview canvas is is crashing but in simulator everything working fine. I assuming it related to @ObservedObject and @Fetchrequest...
在这里
不起作用
import SwiftUI
import CoreData
struct TemplateEditor: View {
@Environment(\.managedObjectContext) var managedObjectContext
@FetchRequest(
entity: GlobalPlaceholders.entity(),
sortDescriptors: [
NSSortDescriptor(keyPath: \GlobalPlaceholders.category, ascending: false),
]
) var placeholders: FetchedResults<GlobalPlaceholders>
@ObservedObject var documentTemplate: Templates
@State private var documentTemplateDraft = DocumentTemplateDraft()
@Binding var editing: Bool
var body: some View {
VStack(){
HStack(){
cancelButton
Spacer()
saveButton
}.padding()
addButton
ForEach(placeholders) {placeholder in
Text(placeholder.name)
}
TextField("Title", text: $documentTemplateDraft.title)
TextField("Body", text: $documentTemplateDraft.body)
.padding()
.frame(width: 100, height:400)
Spacer()
}
...
}
struct TemplateEditor_Previews: PreviewProvider {
static var previews: some View {
let managedObjectContext = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
let request = NSFetchRequest<NSFetchRequestResult>(entityName: "Templates")
request.sortDescriptors = [NSSortDescriptor(keyPath: \Templates.created, ascending: false)]
let documentTemplate = try! managedObjectContext.fetch(request).first as! Templates
return TemplateEditor(documentTemplate: documentTemplate, editing: .constant(true)).environment(\.managedObjectContext, managedObjectContext).environmentObject(documentTemplate)
}
}
预期会生成预览
推荐答案
如果没有数据,我不确定您的try行是否可以工作。
I'm not sure if your try line will work if there is no data.
let documentTemplate = try! managedObjectContext.fetch(request).first as! Templates
为了使我的工作正常,我创建了一个要使用的测试项目。像这样:
To get mine to work I created a test Item to use. Like this:
struct DetailView_Previews: PreviewProvider {
static var previews: some View {
let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
//Test data
let newEvent = Event.init(context: context)
newEvent.timestamp = Date()
return DetailView(event: newEvent).environment(\.managedObjectContext, context)
}
}
我还注意到,我需要较早的托管CoreData视图的tabView中的.environment(.managedObjectContext,context)代码。否则预览将失败。
I've also noticed that I needed the .environment(.managedObjectContext, context) code in an earlier tabView that hosted the CoreData views or the preview would fail.
这篇关于SwiftUI预览画布和核心数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!