我是Swift的新手,我正在努力学习如何使用Core Data.但是我收到了这个错误,我不确定我做错了什么.我在网上搜索并尝试了一些东西,但我无法做到.
Failed to call designated initializer on NSManagedObject class 'FirstCoreData.Course'
Run Code Online (Sandbox Code Playgroud)
当这一行执行时:
ncvc.currentCourse = newCourse
Run Code Online (Sandbox Code Playgroud)
在这个功能:
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
}
}
Run Code Online (Sandbox Code Playgroud)
由课程实体的"创建NSManagedObject子类..."生成的类:
import Foundation
import CoreData
class Course: NSManagedObject {
// Insert code here to add functionality to your managed object subclass
}
Run Code Online (Sandbox Code Playgroud)
和:
import Foundation
import CoreData
extension Course {
@NSManaged var title: String?
@NSManaged var author: String?
@NSManaged var releaseDate: NSDate?
}
Run Code Online (Sandbox Code Playgroud)
pba*_*sdf 71
问题不在于您的问题中的代码,而是在您作为对其他答案的评论中包含的代码段中:
var currentCourse = Course()
Run Code Online (Sandbox Code Playgroud)
这不只是声明currentCourse为类型Course,它还Course使用标准init方法创建实体的实例.明确禁止这样做:您必须使用指定的初始化程序:init(entity entity: NSEntityDescription,
insertIntoManagedObjectContext context: NSManagedObjectContext?).这是在苹果文档中描述这里.
我怀疑你没有使用上面的var定义创建的实例,所以只需将它定义为类型Course?:
var currentCourse : Course?
Run Code Online (Sandbox Code Playgroud)
由于它是可选的,因此您无需设置初始值,但无论何时使用它都需要打开该值.
小智 14
我遇到过同样的问题.并实例化像这样的对象,对于你的课程,它将是这样的:
var currentCourse = Course.init(entity: NSEntityDescription.entityForName("Course", inManagedObjectContext:mox)!, insertIntoManagedObjectContext: mox)
Run Code Online (Sandbox Code Playgroud)
代替:
var currentCourse = Course()
Run Code Online (Sandbox Code Playgroud)
Fab*_*Fab 12
最简单的方法是:
在AppDelegate中(括号外):
let appDelegate = UIApplication.shared.delegate as! AppDelegate
let context = appDelegate.persistentContainer.viewContext
Run Code Online (Sandbox Code Playgroud)
并在代码中:
let currentCourse = Course(context:context)
Run Code Online (Sandbox Code Playgroud)
现在您已创建了您的实体.但不要忘记保存:
appDelegate.saveContext()
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
23400 次 |
| 最近记录: |