Resolving'无法调用NSManagedObject类上的指定初始化器' [英] Resolving 'Failed to call designated initializer on NSManagedObject class'
问题描述
我刚开始使用Swift,我正在学习如何使用Core Data。但我得到这个错误,我不知道我做错了什么。我已经在线搜索,并尝试了几件事,但我不能正确。
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'
此行执行时:
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
}
}
通过创建NSManagedObject子类...为课程实体生成的类:
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
}
和:
import Foundation
import CoreData
extension Course {
@NSManaged var title: String?
@NSManaged var author: String?
@NSManaged var releaseDate: NSDate?
}
推荐答案
不在您的问题中的代码,但在您作为注释包含在另一个答案的代码段中:
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()
这不仅仅是声明 currentCourse
为课程
,它还使用标准创建
方法。这是明确不允许的:你必须使用指定的初始化:课程
实体的实例> init init(entity entity:NSEntityDescription,
。有关详情,请参阅Apple文档在这里。
insertIntoManagedObjectContext context:NSManagedObjectContext?)
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.
我怀疑你没有使用上面var定义创建的实例,所以只需将它定义为type 课程?
:
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.
这篇关于Resolving'无法调用NSManagedObject类上的指定初始化器'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!