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?
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