0

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?

Community
  • 1
  • 1
Harish
  • 1,374
  • 17
  • 39

2 Answers2

6

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
Michael
  • 8,891
  • 3
  • 29
  • 42
  • Hi, thanks for your response. If I do that for some reason the code `firstEntity.firstAttribute` won't work. How would I reference the attributes in each entity using your code? – Harish Feb 27 '16 at 01:25
1

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()
Fab
  • 816
  • 8
  • 17