1

I'm using 'CoreData', I made a 'NSManagedObject' type class of my Entity named 'Project', but when I open the 'ViewController' where I initialize the class as a property, I get this error

 2015-12-09 14:15:54.961 MyProject[790:17582] CoreData: error: Failed to call designated initializer on NSManagedObject class 'MyProject.Project' 

In my Project NSManagedObject class I have a method to add a child NSManagedObject into a NSOrderdSet:

 class Project: NSManagedObject {


func requestAddNewWeek (value : Content) {

    guard let mutableCopyOfSet = projectContent?.mutableCopy() as? NSMutableOrderedSet else {
        return
    }

    mutableCopyOfSet.addObject(value)

    projectContent = mutableCopyOfSet.copy() as? NSOrderedSet
}

}

But because The 'Project' does not initialize correctly, every time I call the method in my viewcontroller an nil is Unwrapped and a error happens.

 @IBAction func saveButtonPressed(sender: AnyObject) {
    //

    let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate

    let managedContext  = appDelegate.managedObjectContext as NSManagedObjectContext

    let entity =  NSEntityDescription.entityForName("WeekContent", inManagedObjectContext:managedContext)

    let newWeek = Content(entity: entity!, insertIntoManagedObjectContext: managedContext)

    //Here I call project, but it unwraps a nil
    project.requestAddNewWeek(newWeek)


    do {
        try managedContext.save()

    } catch let error as NSError  {
        print("Could not save \(error), \(error.userInfo)")
    }
    print(entity)
}

Here is how I defined 'Project' in my ViewController:

 var project : Project = Project()

How do I fix this.

vadian
  • 274,689
  • 30
  • 353
  • 361
Len_X
  • 825
  • 11
  • 29
  • 1
    http://stackoverflow.com/questions/14671478/coredata-error-failed-to-call-designated-initializer-on-nsmanagedobject-class check out this one – evnaz Dec 09 '15 at 12:47

1 Answers1

2

You cannot use the default initializer () on NSManagedObject because the object relies strongly on the managed object context of Core Data.

The designated initializer – which must be used – is

init(entity entity: NSEntityDescription, insertIntoManagedObjectContext context: NSManagedObjectContext?)
vadian
  • 274,689
  • 30
  • 353
  • 361
  • Can you maybe show me how to add this into my code – Len_X Dec 09 '15 at 13:31
  • You need the entity description object and the managed object context of the Core Data stack. Declare the variable as optional, implicit unwrapped optional or (closest to Swift's philosophy) initialize it lazily. Or take a look at the mentioned links. – vadian Dec 09 '15 at 13:42