【问题标题】:Failed to call Designated Initializer on NSManagedObject Class -- CoreData调用 NSManagedObject 类上的指定初始化程序失败 - CoreData
【发布时间】:2016-02-27 01:07:41
【问题描述】:

我真的被这个问题困住了,我参考了this stackoverflow 帖子,但我的应用程序仍然因这个问题而崩溃:

在 NSManagedObject 类上调用指定初始化程序失败

所以,我有多个实体,并且我将NSManagedObject 子类化了。假设我有名为:FirstEntity, SecondEntity, ThirdEntity, Fourth Entity, FifthEntity. 的实体,我们还假设我在每个实体中有两个名为 firstAttribute, secondAttribute 的属性。我进入xcdatamold 打开编辑器,然后选择为我的所有实体创建 NSManagedObject 子类。然后我想实例化每个新的NSManagedObject 子类,这样我就可以访问FirstEntity 中的属性。所以我写了这段代码:

let firstEntity = FirstEntity()

然后当我运行应用程序时它崩溃了,所以我用 stackoverflow 帖子的提示进一步编辑它,现在这是我的代码:

let firstEntityName = NSEntityDescription.entityForName("FirstEntity", inManagedObjectContext: managedObject)

let firstEntity = FirstEntity.init(entity: firstEntity!, insertIntoManagedObjectContext: managedObject)

但是,我的代码仍然崩溃。我真的一无所知,因为与上述问题有关的所有堆栈溢出帖子都说要执行上述操作,但我的代码仍然无法在 NSManagedObject 类上调用指定初始化程序而崩溃 strong> 错误。

有什么建议吗?

【问题讨论】:

    标签: swift core-data nsmanagedobject


    【解决方案1】:

    您不应该通过初始化程序自己创建托管对象。相反,您调用 NSEntityDescription 的 insertNewObjectForEntityForName:inManagedObjectContext: 函数。大致如下:

    let firstEntity = NSEntityDescription.insertNewObjectForEntityForName("FirstEntity", inManagedObjectContext: managedObject)
    

    上面将firstEntity设置为NSManagedObject的一个实例。假设您已经通过 Interface Builder 创建了 NSManagedObject 的 FirstEntity 子类,您可以改为使用:

    let firstEntity = NSEntityDescription.insertNewObjectForEntityForName("FirstEntity", inManagedObjectContext: managedObject) as! FirstEntity
    firstEntity.firstAttribute = // Whatever
    

    【讨论】:

    • 您好,感谢您的回复。如果我出于某种原因这样做,代码firstEntity.firstAttribute 将不起作用。我将如何使用您的代码引用每个实体中的属性?
    【解决方案2】:

    最简单的方法是这样的:

    • 在 applicationDelegate 中定义上下文的引用
    • 通过传递上下文来实例化变量

    在 AppDelegate 中(括号外):

    let appDelegate = UIApplication.shared.delegate as! AppDelegate
    let context = appDelegate.persistentContainer.viewContext
    

    在代码中:

    let firstEntity = FirstEntity(context:context)
    

    现在您已经创建了实体。但不要忘记保存:

    appDelegate.saveContext()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-10-19
      • 1970-01-01
      • 2013-01-18
      • 1970-01-01
      • 1970-01-01
      • 2023-03-12
      相关资源
      最近更新 更多