Swift CoreData:错误:无法在 NSManagedObject 类“NSManagedObject"上调用指定的初始值设定项 [英] Swift CoreData: error: Failed to call designated initializer on NSManagedObject class 'NSManagedObject'
问题描述
我正在使用核心数据在 vc1 中保存一个类别,并希望将列表属性添加到 vc2 中的列表中.我的数据模型是许多列表属性的一个类别.
I'm using core data to save a category in vc1 and want to add list properties to a list in vc2. My data model is one category to many list properties.
我正在 vc1 中添加这样的类别:
I'm adding the category like this in vc1:
func createNewCategory() {
var category: NSManagedObject! = NSEntityDescription.insertNewObjectForEntityForName("Category", inManagedObjectContext: self.context) as NSManagedObject
category.setValue(self.categoryTextField.text, forKey: "name")
var error: NSError? = nil
self.context.save(&error)
}
在vc2中设置数据:
func setupCoreData() {
var appDelegate: AppDelegate = (UIApplication.sharedApplication()).delegate as AppDelegate
self.context = appDelegate.managedObjectContext!
var request: NSFetchRequest = NSFetchRequest(entityName: "Category")
if (self.context.executeFetchRequest(request, error: nil)) {
var error: NSError? = nil
self.listData = self.context.executeFetchRequest(request, error: &error)
self.managedObject = self.listData.objectAtIndex(0) as NSManagedObject
}
}
它在最后一行崩溃:self.managedObject = ...
说:
It crashes on the last row: self.managedObject = ...
saying:
CoreData: error: Failed to call designated initializer on NSManagedObject class 'NSManagedObject'
如果我放置一个断点并打印数组,则托管对象在数组中.怎么了?
The managed object is in the array if I put a break point and print the array. What's wrong?
推荐答案
专用初始化器是
class func insertNewObjectForEntityForName(_ entityName: String!,
inManagedObjectContext context: NSManagedObjectContext!) -> AnyObject!
显然,您不是在插入新对象,因此您确实需要一个可选值.也许您将类变量 managedObject
声明为 NSManagedObject!
?尝试将其设置为 NSManagedObject?
并将运算符更改为 as?
.
Clearly, you are not inserting a new object, so you really want an optional value. Maybe you declared your class variable managedObject
as NSManagedObject!
? Try setting it to NSManagedObject?
and also change the operator to as?
.
这篇关于Swift CoreData:错误:无法在 NSManagedObject 类“NSManagedObject"上调用指定的初始值设定项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!