Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
952 views
in Technique[技术] by (71.8m points)

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

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...