我是Swift的新手,我正在尝试学习如何使用核心数据。但是我得到了这个错误,我不确定我做错了什么。我已经在网上搜索并尝试了一些东西,但我不能得到正确的。
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...“生成的类对于课程实体:
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?
}
发布于 2015-10-24 01:03:11
问题不在于您问题中的代码,而在于您作为注释包含在另一个答案中的代码片段:
var currentCourse = Course()
这不仅仅是将currentCourse
声明为Course
类型,它还使用标准的init
方法创建Course
实体的一个实例。这显然是不允许的:您必须使用指定的初始化器:init(entity entity: NSEntityDescription, insertIntoManagedObjectContext context: NSManagedObjectContext?)
。这在Apple Documentation here中有描述。
我怀疑您从未使用过由上面的var定义创建的实例,因此只需将其定义为Course?
类型即可
var currentCourse : Course?
因为它是可选的,所以您不需要设置初始值,尽管每次使用它时都需要解开该值。
发布于 2016-02-05 03:46:28
我也有同样的问题。像这样实例化对象,对于你的课程来说,它应该是这样的:
var currentCourse = Course.init(entity: NSEntityDescription.entityForName("Course", inManagedObjectContext:mox)!, insertIntoManagedObjectContext: mox)
而不是:
var currentCourse = Course()
发布于 2017-04-24 16:51:25
我在带有Swift 3.1的Xcode 8.3.2中使用了这一点。
NSEntityDescription.insertNewObject(forEntityName: String(describing: type(of: Record())), into: managedObjectContext) as! Record
并收到相同的错误消息。但是这个数据是插入到数据库中的。所以也许这无关紧要。
https://stackoverflow.com/questions/33301250
复制相似问题