问题
I have really been stuck on this issue and I have referred to this stackoverflow post but my application still crashes with the issue:
Failed to call Designated Initializer on NSManagedObject Class
So, I have multiple entities and I have subclassed the NSManagedObject
. Let's pretend I have entities named: FirstEntity, SecondEntity, ThirdEntity, Fourth Entity, FifthEntity.
Let's also pretend I have two attributes named firstAttribute, secondAttribute
in each Entity. I went into the xcdatamold
opened up the editor and then selected create NSManagedObject Subclass for all of my entities. Then I wanted to instantiate of each of these new NSManagedObject
Subclasses so I could access the attributes inside the FirstEntity
. So I wrote this code:
let firstEntity = FirstEntity()
Then when I run the app it crashes, so I edited it further with a hint from the stackoverflow post and now this is my code:
let firstEntityName = NSEntityDescription.entityForName("FirstEntity", inManagedObjectContext: managedObject)
let firstEntity = FirstEntity.init(entity: firstEntity!, insertIntoManagedObjectContext: managedObject)
However, my code still is crashing. I am really clueless, because all of the stack overflow posts pertaining to the issue said to do the above, but my code is still crashing with the Failed to call Designated Initializer on NSManagedObject Class error.
Any suggestions?
回答1:
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
回答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 firstEntity = FirstEntity(context:context)
Now you have your entity created. But don't forget to save with:
appDelegate.saveContext()
来源:https://stackoverflow.com/questions/35664476/failed-to-call-designated-initializer-on-nsmanagedobject-class-coredata