Core Data error: Failed to load model, 'An NSManagedObject of class 'MyApp.Item' must have a valid NSEntityDescription

Viewed 382

I created a Swift project with no coredata, only to add some later. I copied the following code from a real template to my project AppDelegate and created my coredata model file. However, As soon as I created a coreData object using the context, I got:

CoreData: error: Failed to load model named coredatatemplate

Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'An NSManagedObject of class 'MyApp.Item' must have a valid NSEntityDescription.

I had to look around to figure out the problem, as I already had done the following:

  • My custom entity had the same Class name and Entity name that matched the coredata file
  • I had selected Current Product Module for Module
  • I had selected the standard Class Definition for Codegen

(Check to make sure these are alright if you're having the same problem.)

enter image description here

The problem persisted and I couldn't find the root cause.

1 Answers

SOLUTION:

What was wrong in my case is that the template code used another name than my CoreData file.

In my AppDelegate:

// MARK: - Core Data stack

lazy var persistentContainer: NSPersistentContainer = {
    
    let container = NSPersistentContainer(name: "DataModel")
    container.loadPersistentStores(completionHandler: { (storeDescription, error) in
        if let error = error as NSError? {
            fatalError("Unresolved error \(error), \(error.userInfo)")
        }
    })
    return container
}()

Using name: "DataModel", which I had to change to match DataModel.xcdatamodeld in my project.

Related