2015-12-09 71 views
1

我使用'CoreData',我做了一个名为'Project'的实体的'NSManagedObject'类型类,但是当我打开'ViewController'时,我将该类初始化为属性,我得到这个错误NSManagedObject未能初始化

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是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) 
} 

这是我如何定义我的视图控制器 '项目':

var project : Project = Project() 

我该如何解决这个问题。

+1

http://stackoverflow.com/questions/14671478/coredata-error-failed-to-call-designated-initializer-on-nsmanagedobject- class check out this – evnaz

回答

2

您不能使用NSManagedObject上的默认初始化程序(),因为该对象强烈依赖于Core Data的受管对象上下文。

指定初始化 - 这必须使用 - 是

init(entity entity: NSEntityDescription, insertIntoManagedObjectContext context: NSManagedObjectContext?) 
+0

您可以告诉我如何将其添加到我的代码中 –

+0

您需要Core Data堆栈的实体描述对象和受管对象上下文。声明变量为可选的,隐式解包可选或(最接近Swift的哲学)懒惰地初始化它。或者看看提到的链接。 – vadian