我正在使用'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'
在我的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
}
}
但是因为'Project'没有正确初始化,所以每当我在viewcontroller中调用该方法时,nil都是Unwrapped并且发生错误。
@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中定义'Project'的方法:
var project : Project = Project()
我该如何解决这个问题。
答案 0 :(得分:2)
您无法在()
上使用默认初始值设定项NSManagedObject
,因为该对象强烈依赖于Core Data的托管对象上下文。
指定的初始化程序 - 必须使用 - 是
init(entity entity: NSEntityDescription, insertIntoManagedObjectContext context: NSManagedObjectContext?)