Failed to call Designated Initializer on NSManagedObject Class — CoreData

…衆ロ難τιáo~ 提交于 2019-12-02 10:11:39

You should not create managed objects yourself through an initializer. Instead, you call NSEntityDescription's insertNewObjectForEntityForName:inManagedObjectContext: function. Along the lines of:

let firstEntity = NSEntityDescription.insertNewObjectForEntityForName("FirstEntity", inManagedObjectContext: managedObject)

The above sets firstEntity as an instance of NSManagedObject. Assuming you have created a FirstEntity subclass of NSManagedObject through Interface Builder, you can instead use:

let firstEntity = NSEntityDescription.insertNewObjectForEntityForName("FirstEntity", inManagedObjectContext: managedObject) as! FirstEntity
firstEntity.firstAttribute = // Whatever

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 firstEntity = FirstEntity(context:context)

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

appDelegate.saveContext()
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!