swift - 以卡片形式呈现时核心数据未保存
问题描述
我正在学习核心数据,所以我的知识有限。我有一个应用程序,我试图在其中存储举重数据,然后将其列出。我有两个视图,一个视图用于添加数据,一个视图用于列出数据。合并代码后,我能够保存数据。一旦我转到不同的视图,数据就不再保存了。
我在 AppDelegate 中遇到的错误是Context in environment is not connected to a persistent store coordinator
这是用于将添加数据视图调用为卡片的代码
@State var showFoo = false
@Environment(\.managedObjectContext) var managedObjectContext
@FetchRequest(fetchRequest: StatItem.getStatItems()) var statItems:FetchedResults<StatItem>
var body: some View {
NavigationView {
Form{
Section(header: Text("Lifts")){
ForEach(self.statItems){StatItem in
StatItemView(lift: StatItem.lift!, createdAt: "\(StatItem.createdAt!)", weight: StatItem.weight ?? "0")
}.onDelete {indexSet in
let deleteItem = self.statItems[indexSet.first!]
self.managedObjectContext.delete(deleteItem)
do {
try self.managedObjectContext.save()
}catch {
print(error) //update this error.
}
}
.onTapGesture {
self.hideKeyboard()
}
}
.font(.headline)
}
.navigationBarTitle(Text("My Lifts"))
.navigationBarItems(leading: Button(action:{ self.showFoo.toggle() } ) {
Image(systemName: "plus.app")
//.renderingMode(.original)
.foregroundColor(.primary)
.font(.system(size: 16, weight: .medium))
.frame(width: 36, height: 36)
.background(Color("background3"))
.clipShape(Circle())
.shadow(color: Color.black.opacity(0.1), radius: 1, x: 0, y: 1)
.shadow(color: Color.black.opacity(0.2), radius: 10, x: 0, y: 10)
}
.sheet(isPresented: $showFoo) {
foo()
}, trailing: EditButton())
}
}
}
添加数据的代码
var liftslist = ["Bench Press","Deadlift","Squat","Back Row","Strict Press"]
@State private var selectedlLiftsList = 0
@State private var currentTab = 0
@State private var newStatItemLift = ""
@State private var newStatItemWeight = ""
@Environment(\.managedObjectContext) var managedObjectContext
@FetchRequest(fetchRequest: StatItem.getStatItems()) var statItems:FetchedResults<StatItem>
var body: some View {
VStack {
NavigationView {
Form{
List {
Section(header: Text("Max Rep")){
Picker(selection: $selectedlLiftsList, label: Text("Select Lift")) {
ForEach(0 ..< liftslist.count ){
Text(self.liftslist[$0])
}
}
HStack{
TextField("Weight", text: self.$newStatItemWeight)
.keyboardType(.numberPad)
Button(action: {
guard self.newStatItemWeight.count > 0 else {return}
let statItem = StatItem(context: self.managedObjectContext)
statItem.lift = self.liftslist[self.selectedlLiftsList]
statItem.createdAt = Date()
statItem.weight = self.newStatItemWeight
do {
try self.managedObjectContext.save()
}catch{
print(error)
print("We didn't save \(self.newStatItemWeight)")
}
self.newStatItemWeight = "" //this cleans the item
})
{
Image(systemName: "plus.circle.fill")
.foregroundColor(.green)
.imageScale(.large)
}
}
}
.font(.headline)
}
}
}
}
}
}
AppDelegate 代码
lazy var persistentContainer: NSPersistentContainer = {
/*
The persistent container for the application. This implementation
creates and returns a container, having loaded the store for the
application to it. This property is optional since there are legitimate
error conditions that could cause the creation of the store to fail.
*/
let container = NSPersistentContainer(name: "StatItem")
container.loadPersistentStores(completionHandler: { (storeDescription, error) in
if let error = error as NSError? {
// Replace this implementation with code to handle the error appropriately.
// fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
/*
Typical reasons for an error here include:
* The parent directory does not exist, cannot be created, or disallows writing.
* The persistent store is not accessible, due to permissions or data protection when the device is locked.
* The device is out of space.
* The store could not be migrated to the current model version.
Check the error message to determine what the actual problem was.
*/
fatalError("Unresolved error \(error), \(error.userInfo)")
}
})
return container
}()
我的课
public class StatItem:NSManagedObject, Identifiable {
@NSManaged public var createdAt:Date?
@NSManaged public var lift:String?
@NSManaged public var weight:String?
}
extension StatItem {
static func getStatItems() -> NSFetchRequest <StatItem> {
let request: NSFetchRequest<StatItem> = StatItem.fetchRequest() as! NSFetchRequest<StatItem>
let sortDescriptor = NSSortDescriptor(key: "createdAt", ascending: true)
request.sortDescriptors = [sortDescriptor]
return request
}
}
解决方案
我想通了,因为我错过了以下内容
.sheet(isPresented: self.$showSheet) {
SheetView()
.environment(\.managedObjectContext, self. managedObjectContext)
}
推荐阅读
- node.js - Node.js XML builder 错误:名称中的字符无效:在创建 XML 文档期间
- drools - 流口水的积累正在更新一个无关紧要的事实
- node.js - VueJS 中的基本 HTTP 请求
- java - com.microsoft.azure:azure-sqldb-spark bulkCopyBatchSize 不起作用
- javascript - 如何记录给定 DOM 对象触发的所有事件?
- google-cloud-platform - 分析语法返回不准确的上下文结果
- php - 如何在不显示的情况下加载 php 文件?(/page.php -> /page)
- go - 附件名称中的 Unicode 字符
- python - 我正在尝试解决 0/1 背包问题,但我得到的输出与零一样多
- html - 非破坏空间(160)和正常空间(32)的宽度不同