core-data - 正在解析 'Failed to call designated initializer on NSManagedObject class'

标签 core-data swift2

我是 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/

相关文章:

swift - 在 Swift 2 中,禁用 NSMenuItem 的正确方法是什么?

swift - 使用通用协议(protocol)作为返回类型调用函数

swift - map 返回的数组顺序

ios - [AppDelegate managedObjectContext] : unrecognized selector sent to instance

swift - 快速获取具有一对多关系的 coredata

ios - Protocol 只能作为泛型约束,因为它有 Self 或 associatedType 要求

ios - 使用 Swift 2.0 更新 UIButton 图像

swift - 如何在 Swift 3 中将自定义类保存为 CoreData 实体的属性?

iphone - 核心数据 - 查找具有重叠日期范围的记录

core-data - 多个 NSEntityDescriptions 声明 NSManagedObject 子类