简体   繁体   中英

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
    newItem.title=title
    newItem.text=text
    newItem.date=date
    newItem.extra=extra
    newItem.backup=backup.integerValue
}
}

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

The key here is

unexpectedly found nil while unwrapping an Optional value

Maybe your backup or backup.integer or any other assigned value is nil. Please debug to check.

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.

DAO

 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!)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM