SwiftUI CoreData 崩溃预览 [英] SwiftUI CoreData crashes preview
问题描述
我有以下代码来绘制汽车列表,数据存储在 coredata 中.
I have the following code to draw a list of cars, data stored in coredata.
但是,当我添加从数据库中获取数据的代码行时,swiftui 预览似乎中断了.
However the swiftui preview seems to break when I add the line of code that fetches data from the databases.
错误日志说明以下内容:
the error logs tells the following:
PotentialCrashError:测试 app.app 可能已经崩溃
PotentialCrashError: test app.app may have crashed
里程 app.app 可能已崩溃.查看~/Library/Logs/DiagnosticReports 从您的任何崩溃日志申请.
mileage app.app may have crashed. Check ~/Library/Logs/DiagnosticReports for any crash logs from your application.
==================================
==================================
|错误域=com.apple.dt.ultraviolet.service 代码=12渲染服务被中断" UserInfo={NSLocalizedDescription=Rendering服务中断}
| Error Domain=com.apple.dt.ultraviolet.service Code=12 "Rendering service was interrupted" UserInfo={NSLocalizedDescription=Rendering service was interrupted}
这是foreach开始和结束的部分导致错误的代码:
this is the code the part where foreach starts and ends causes the error:
import SwiftUI
struct CarListView: View {
@Environment(\.managedObjectContext) var managedObjectContext
@FetchRequest(fetchRequest: Car.all()) var cars: FetchedResults<Car>
var body: some View {
NavigationView {
ZStack {
List {
Section(header: Text("Cars")) {
ForEach(self.cars, id: \.numberPlate) { car in
HStack {
VStack(alignment: .leading) {
Text(car.name)
Text(car.numberPlate)
}
}
}
}
}
}
}
}
}
struct CarListView_Previews: PreviewProvider {
static var previews: some View {
CarListView()
}
}
推荐答案
该问题似乎与以下事实有关:它无法以某种方式获得允许在预览模式下获取数据的上下文.通过在预览模式下手动执行此操作,它可以解决问题.
The issue seems to be related to the fact it couldn't somehow get a context which allows to fetch the data in preview mode. By manually doing so for preview mode it fixes the issue.
struct CarListView_Previews: PreviewProvider {
static var previews: some View {
let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
return CarListView().environment(\.managedObjectContext, context)
}
}
这篇关于SwiftUI CoreData 崩溃预览的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!