我真的被这个问题困住了,我引用了this stackoverflow 帖子,但我的应用程序仍然因问题而崩溃:
Failed to call Designated Initializer on NSManagedObject Class
所以,我有多个实体,并且我已经对 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 类上的指定初始化程序而崩溃强>错误。
有什么建议吗?
最佳答案
您不应该通过初始化器自己创建托管对象。相反,您调用 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
关于swift - 无法调用 NSManagedObject 类上的指定初始化程序 -- CoreData,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35664476/