Reputation: 524
I am trying to load file from Core Data as I did before. My CoreData stack as follows:
import Foundation
import CoreData
class SaveData:NSObject {
lazy var persistentContainer: NSPersistentContainer = {
let container = NSPersistentContainer(name: "DataModel")
container.loadPersistentStores(completionHandler: {
storeDescription, error in
if let error = error {
fatalError("Could load data store: \(error)") } })
return container }()
lazy var managedObjectContext: NSManagedObjectContext = persistentContainer.viewContext
}
I have no trouble of saving data when saving function is trigger. But having trouble of fetching data. My fetch method like this:
var saveData = SaveData()
var locations = [Location]()
override func viewDidLoad() {
super.viewDidLoad()
let fetchRequest = NSFetchRequest<Location>() // 2
let entity = Location.entity()
fetchRequest.entity = entity // 3
let sortDescriptor = NSSortDescriptor(key: "date", ascending: true)
fetchRequest.sortDescriptors = [sortDescriptor]
do {
locations = try saveData.managedObjectContext.fetch(fetchRequest)
} catch {
fatalCoreDataError(error)
}
}
When fetching the data from CoreData, app crashes. The debugs area says: 2019-10-02 20:44:29.780267+0800 MyLocation[20870:2214196] [error] error: No NSEntityDescriptions in any model claim the NSManagedObject subclass 'Location' so +entity is confused. Have you loaded your NSManagedObjectModel yet ? CoreData: error: No NSEntityDescriptions in any model claim the NSManagedObject subclass 'Location' so +entity is confused. Have you loaded your NSManagedObjectModel yet ? 2019-10-02 20:44:29.780387+0800 MyLocation[20870:2214196] [error] error: +[Location entity] Failed to find a unique match for an NSEntityDescription to a managed object subclass CoreData: error: +[Location entity] Failed to find a unique match for an NSEntityDescription to a managed object subclass 2019-10-02 20:44:29.789644+0800 MyLocation[20870:2214196] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'executeFetchRequest:error: A fetch request must have an entity.'
I have tried the solution I can find, nothing works at the moment. How to resolve this issue? Thanks in advance.
Upvotes: 1
Views: 1268
Reputation: 825
I've fixed this issue before.
First I was declaring a method named fetchRequest()
on the managed object like that:
extension OrderType {
@nonobjc public class func fetchRequest() -> NSFetchRequest<OrderType> {
return NSFetchRequest<OrderType>(entityName: "OrderType")
}
@NSManaged public var orderType: String?
@NSManaged public var orderTypeId: Int32
@NSManaged public var order: NSSet?
}
The app was crashing on this line:
let itemCount = try managedObjectContext.count(for: OrderType.fetchRequest())
In order to fix this crash I've changed the code to:
let fetchRequest = OrderType.fetchRequest()
let itemCount = try managedObjectContext.count(for: fetchRequest)
the crash disappeared! hope it works with you too ^^
Upvotes: 1