我是 Swift 新手,我正在尝试学习如何使用 Core Data。但我收到了这个错误,我不确定我做错了什么。我在网上搜索并尝试了一些方法,但我无法得到正确的结果。
Failed to call designated initializer on NSManagedObject class 'FirstCoreData.Course'
当该行执行时:
ncvc.currentCourse = newCourse
在此函数中:
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
}
}
通过“Create NSManagedObject Subclass...”为类(class)实体生成的类:
import Foundation
import CoreData
class Course: NSManagedObject {
// Insert code here to add functionality to your managed object subclass
}
还有:
import Foundation
import CoreData
extension Course {
@NSManaged var title: String?
@NSManaged var author: String?
@NSManaged var releaseDate: NSDate?
}
最佳答案
问题不在于您问题中的代码,而在于您作为其他答案的注释包含的代码片段:
var currentCourse = Course()
这不仅仅是声明 currentCourse
类型为Course
,它还会创建 Course
的实例使用标准的实体init
方法。这是明确不允许的:您必须使用指定的初始化程序:init(entity entity: NSEntityDescription,
insertIntoManagedObjectContext context: NSManagedObjectContext?)
。 Apple 文档 here 对此进行了描述。 .
我怀疑您从未使用过上述 var 定义创建的实例,因此只需将其定义为 Course?
类型即可:
var currentCourse : Course?
由于它是可选的,因此您不需要设置初始值,但在使用时需要解开该值。
关于core-data - 正在解析 'Failed to call designated initializer on NSManagedObject class',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33301250/