Swift CoreData: error: Failed to call designated initializer on NSManagedObject class 'NSManagedObject'

随声附和 提交于 2019-11-28 04:23:38

问题


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.

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

Setting up the data in 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
    }
}

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?


回答1:


The dedicated initializer is

class func insertNewObjectForEntityForName(_ entityName: String!,
   inManagedObjectContext context: NSManagedObjectContext!) -> AnyObject!

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?.




回答2:


An entity in CoreData is equivalent to a class. Did you add the entity to your managed object model, and subclass the entity? (Check out the programming guide for a fuller background.)



来源:https://stackoverflow.com/questions/25504799/swift-coredata-error-failed-to-call-designated-initializer-on-nsmanagedobject

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!