SwiftUI @FetchRequest crashes the app and returns error

本小妞迷上赌 提交于 2021-02-05 07:51:29

问题


I am trying to use core data within my mac app with SwiftUI using Xcode 11. I have checked "Using Core Data" when creating the project. I also have created the entity (called VisitedCases) and used editor to create NSManagedObject Subclass files. I also have set the Codegen to Manual/none. Here is the code in the generated NSManagedObject files:

VisitedCases+CoreDataProperties.swift

extension VisitedCases {

    @nonobjc public class func fetchRequest() -> NSFetchRequest<VisitedCases> {
        return NSFetchRequest<VisitedCases>(entityName: "VisitedCases")
    }

    @NSManaged public var caseNumber: String

} 

VisitedCases+CoreDataClass.swift

@objc(VisitedCases)
public class VisitedCases: NSManagedObject {

}

I called the @Environment variable and the @FetchRequest in ContentView.swift as:

struct ContentView: View {
    @Environment(\.managedObjectContext) var managedObjectContext

    @FetchRequest(entity: VisitedCases.entity(),
                  sortDescriptors: []
                  ) var orders: FetchedResults<VisitedCases>
//@State vars and the rest of the code
}

However, when I run, the app crashed as soon as launch with the following errors in the output:

2020-02-23 18:36:16.889306+0330 ImageSelector[17874:149503] [error] error: No NSEntityDescriptions in any model claim the NSManagedObject subclass 'VisitedCases' so +entity is confused.  Have you loaded your NSManagedObjectModel yet ?
CoreData: error: No NSEntityDescriptions in any model claim the NSManagedObject subclass 'VisitedCases' so +entity is confused.  Have you loaded your NSManagedObjectModel yet ?
2020-02-23 18:36:16.889389+0330 ImageSelector[17874:149503] [error] error: +[VisitedCases entity] Failed to find a unique match for an NSEntityDescription to a managed object subclass
CoreData: error: +[VisitedCases entity] Failed to find a unique match for an NSEntityDescription to a managed object subclass
2020-02-23 18:36:16.921131+0330 ImageSelector[17874:149503] executeFetchRequest:error: A fetch request must have an entity.

I also have a function that saves a string to storage and seems to work just fine:

    func addCaseNumber (caseNo: String) {
        guard caseNo != "" else {return}
        let newCaseNumber = VisitedCases(context: self.managedObjectContext)
        newCaseNumber.caseNumber = caseNo
        do {
         try self.managedObjectContext.save()
         print("Case number saved.")
        } catch {
         print(error.localizedDescription)
         }
    }

What is wrong with my code and what should I do to fix it?


回答1:


In the @enviromentVAr, sometimes, you need to set the enviroment by yourself.

 let managedObjectContext: NSManagedObjectContext =  ((UIApplication.shared.delegate as? AppDelegate)?.persistentContainer.viewContext)!

 ContentView().environment(\.managedObjectContext, managedObjectContext)

Then the managedObjectContext can work.

 @Environment(\.managedObjectContext) var managedObjectContext



回答2:


Try assigning your managedObjectContext in your ContentView like this

let managedObjectContext: NSManagedObjectContext =  ((UIApplication.shared.delegate as? AppDelegate)?.persistentContainer.viewContext)!

If this works it means that your @Environment var isn't working.

To find out where the break happens start with the SceneDelegate having

let contentView = ContentView().environment(\.managedObjectContext, context)

Then see where the connection with Environment is being broken

Put something like this in all your views to see which doesn't get the Environment variable.

@Environment(\.managedObjectContext) var managedObjectContext
     var body: some View {
         print("MOC = ")
         print(managedObjectContext.name ?? "broken")
     return Text("Hello World!")
}

When you find the break reestablish it with

YourBrokenView().environment(\.managedObjectContext, managedObjectContext)


来源:https://stackoverflow.com/questions/60363726/swiftui-fetchrequest-crashes-the-app-and-returns-error

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!