如何解决当显示为卡时,核心数据未保存
我正在学习核心数据,所以我的知识有限。我有一个要在其中存储举重数据然后将其列出的应用程序。我有两个视图,一个视图用于添加数据,一个视图用于列出数据。合并代码后,我可以保存数据。曾经有一次我去不同的视图,数据不再保存。
我在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,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)
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。