Japes Japes - 1 year ago 426
Swift Question

CoreData: error: Failed to call designated initializer on NSManagedObject class failing on create

I have looked at other questions and tried their solutions but the error persists.

Also, this is my first iOS project so please explain like I'm five >.<

Ok, so I have a diary entry entity, looking like such:

import Foundation
import CoreData

class DiaryEntry: NSManagedObject {

@NSManaged var title: String
@NSManaged var text: String
@NSManaged var date: NSDate
@NSManaged var extra: String
@NSManaged var backup: NSNumber

as well, i have a DAO file like this (abridged)
import Foundation
import CoreData

class coreDataDao : NSManagedObject, DiaryDAO{
func createEntry(title:String,text:String,date:NSDate,backup:NSNumber,extra:String){
let newItem = NSEntityDescription.insertNewObjectForEntityForName("DiaryEntry", inManagedObjectContext: self.managedObjectContext!) as! DiaryEntry

and finally, called in my viewcontroller, i have this function:

let managedObjectContext = (UIApplication.sharedApplication().delegate as! AppDelegate).managedObjectContext
func jTest(){
var dao = coreDataDao()
dao.createEntry("a title",text:"some text", date: NSDate(), backup: 2, extra: "extras")

However when the code runs, I get the following error:

MyApp[9786:438760] CoreData: error: Failed to call designated initializer on NSManagedObject class 'MyAppName.coreDataDao'
fatal error: unexpectedly found nil while unwrapping an Optional value

Ive been trying things all day, including most of the SO solutions regarding this error but I can't get it going. Thanks in advance

Answer Source

The solution turned out to be dealing with ManagedObjectContext. I was atempting to generate it in my DAO file, when it needed to be passed from the ViewController.


 class func createEntry(title:String,context:NSManagedObjectContext)->DiaryEntry{

    if let newItem = NSEntityDescription.insertNewObjectForEntityForName("DiaryEntry", inManagedObjectContext: context) as? DiaryEntry{

and viewcontroller

coreDataDao.createEntry("a title",context: self.managedObjectContext!)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download