Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

core data - Resolving 'Failed to call designated initializer on NSManagedObject class'

I'm new to Swift and I'm trying to learn how to use Core Data. But I'm getting this error and I'm not sure what I've done wrong. I've searched online and tried a few things but I can't get it right.

Failed to call designated initializer on NSManagedObject class 'FirstCoreData.Course'

When this line executes:

ncvc.currentCourse = newCourse

In this function:

class TableViewController: UITableViewController, AddCourseViewControllerDelegate {

var managedObjectContext = NSManagedObjectContext.init(concurrencyType: NSManagedObjectContextConcurrencyType.MainQueueConcurrencyType)

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
    if segue.identifier == "addCourse" {
        let ncvc = segue.destinationViewController as! NewCourseViewController
        ncvc.delegate = self

        let newCourse = NSEntityDescription.insertNewObjectForEntityForName("Course", inManagedObjectContext: self.managedObjectContext) as! Course
        ncvc.currentCourse = newCourse

    }
}

Class generated by "Create NSManagedObject Subclass..." for Course entity:

import Foundation
import CoreData

class Course: NSManagedObject {

// Insert code here to add functionality to your managed object subclass

}

And:

import Foundation
import CoreData

extension Course {

    @NSManaged var title: String?
    @NSManaged var author: String?
    @NSManaged var releaseDate: NSDate?

}
question from:https://stackoverflow.com/questions/33301250/resolving-failed-to-call-designated-initializer-on-nsmanagedobject-class

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

1 Answer

0 votes
by (71.8m points)

The problem lies not in the code in your question, but in the snippet you included as comments to the other answer:

var currentCourse = Course()

This doesn't just declare currentCourse to be of type Course, it also creates an instance of the Course entity using the standard init method. This is expressly not allowed: You must use the designated initialiser: init(entity entity: NSEntityDescription, insertIntoManagedObjectContext context: NSManagedObjectContext?). This is described in the Apple Documentation here.

I suspect you do not ever use the instance created by the above var definition, so just define it as being of type Course?:

var currentCourse : Course?

Since it is optional, you do not need to set an initial value, though you will need to unwrap the value whenever it is used.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...