Swift CoreData: error: failed to call the designated initializer in class NSManagedObject 'NSManagedObject'

I am using basic data to save a category in vc1 and want to add list properties to the list in vc2. My data model is one category for many list properties.

I add this category to vc1:

func createNewCategory() { var category: NSManagedObject! = NSEntityDescription.insertNewObjectForEntityForName("Category", inManagedObjectContext: self.context) as NSManagedObject category.setValue(self.categoryTextField.text, forKey: "name") var error: NSError? = nil self.context.save(&error) } 

Data setup in vc2:

 func setupCoreData() { var appDelegate: AppDelegate = (UIApplication.sharedApplication()).delegate as AppDelegate self.context = appDelegate.managedObjectContext! var request: NSFetchRequest = NSFetchRequest(entityName: "Category") if (self.context.executeFetchRequest(request, error: nil)) { var error: NSError? = nil self.listData = self.context.executeFetchRequest(request, error: &error) self.managedObject = self.listData.objectAtIndex(0) as NSManagedObject } } 

Crash on the last line: self.managedObject = ... :

 CoreData: error: Failed to call designated initializer on NSManagedObject class 'NSManagedObject' 

The managed entity is in the array if I place a breakpoint and print the array. What's wrong?

+5
source share
2 answers

Assigned Initializer

 class func insertNewObjectForEntityForName(_ entityName: String!, inManagedObjectContext context: NSManagedObjectContext!) -> AnyObject! 

Obviously, you are not inserting a new object, so you really need an extra value. Maybe you declared a variable of the managedObject class as NSManagedObject! ? Try installing it on NSManagedObject? , and also change the operator to as? .

+6
source

An entity in CoreData is equivalent to a class. Have you added the object to the managed object model and subclassed the object? (Check out the programming guide for a more complete background.)

+1
source

Source: https://habr.com/ru/post/1201148/


All Articles