Resolving 'Failed to call designated initializer on NSManagedObject class'

Solution 1:

The problem lies not in the code in your question, but in the snippet you included as comments to the other answer:

var currentCourse = Course()

This doesn't just declare currentCourse to be of type Course, it also creates an instance of the Course entity using the standard init method. This is expressly not allowed: You must use the designated initialiser: init(entity entity: NSEntityDescription, insertIntoManagedObjectContext context: NSManagedObjectContext?). This is described in the Apple Documentation here.

I suspect you do not ever use the instance created by the above var definition, so just define it as being of type Course?:

var currentCourse : Course?

Since it is optional, you do not need to set an initial value, though you will need to unwrap the value whenever it is used.

Solution 2:

The simplest way is this:

  • Define in the applicationDelegate a reference for the context
  • Instantiate the variable by passing the context

In the AppDelegate (outside the brackets):

let appDelegate = UIApplication.shared.delegate as! AppDelegate
let context = appDelegate.persistentContainer.viewContext

And in the code:

let currentCourse = Course(context:context)

Now you have your entity created. But don't forget to save with:

appDelegate.saveContext()