当显示为卡时,核心数据未保存

问题描述

我正在学习核心数据,所以我的知识有限。我有一个要在其中存储举重数据然后将其列出的应用程序。我有两个视图,一个视图用于添加数据,一个视图用于列出数据。合并代码后,我可以保存数据。曾经有一次我去不同的视图,数据不再保存。

我在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)
        }

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...