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?