Ios NSManagedObject未能初始化
我使用的是“CoreData”,我为我的实体创建了一个名为“Project”的“NSManagedObject”类型的类,但当我打开“ViewController”并将该类初始化为属性时,出现了此错误Ios NSManagedObject未能初始化,ios,core-data,swift2,nsmanagedobject,Ios,Core Data,Swift2,Nsmanagedobject,我使用的是“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' 在
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
}
}
但由于“项目”没有正确初始化,每次我在viewcontroller中调用该方法时,都会打开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()
如何解决此问题。您不能在
NSManagedObject
上使用默认初始值设定项()
,因为该对象强烈依赖核心数据的托管对象上下文
指定的初始值设定项(必须使用)为
init(entity entity: NSEntityDescription, insertIntoManagedObjectContext context: NSManagedObjectContext?)
查看这一个你可以告诉我如何将其添加到我的代码中吗?你需要核心数据堆栈的实体描述对象和托管对象上下文。将变量声明为可选、隐式展开可选或(最接近Swift的原理)延迟初始化。或者看看上面提到的链接。