【问题标题】:NSManagedObject failing to Initialize [duplicate]NSManagedObject 无法初始化 [重复]
【发布时间】:2015-12-09 12:42:22
【问题描述】:

我正在使用“CoreData”,我为名为“Project”的实体创建了一个“NSManagedObject”类型类,但是当我打开将类初始化为属性的“ViewController”时,出现此错误

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

在我的项目 NSManagedObject 类中,我有一个方法可以将子 NSManagedObject 添加到 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
}

}

但是因为“项目”没有正确初始化,每次我在视图控制器中调用该方法时,都会打开一个 nil 并发生错误。

 @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)
}

这是我在 ViewController 中定义“项目”的方式:

 var project : Project = Project()

我该如何解决这个问题。

【问题讨论】:

标签: ios core-data swift2 nsmanagedobject


【解决方案1】:

您不能在NSManagedObject 上使用默认初始化程序(),因为该对象强烈依赖于Core Data 的托管对象上下文。

指定的初始化器——必须使用——是

init(entity entity: NSEntityDescription, insertIntoManagedObjectContext context: NSManagedObjectContext?)

【讨论】:

  • 你能告诉我如何将它添加到我的代码中
  • 你需要核心数据栈的实体描述对象和托管对象上下文。将变量声明为可选,隐式展开可选或(最接近 Swift 的哲学)懒惰地初始化它。或查看上述链接。
猜你喜欢
  • 2016-12-30
  • 1970-01-01
  • 2020-03-30
  • 2014-10-19
  • 1970-01-01
  • 2012-11-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多