解决“无法在 NSManagedObject 类上调用指定的初始化程序" [英] Resolving 'Failed to call designated initializer on NSManagedObject class'

查看:25
本文介绍了解决“无法在 NSManagedObject 类上调用指定的初始化程序"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 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 声明为 Course 类型,它还使用标准 Course 实体创建了一个实例code>init 方法.这是明确不允许的:您必须使用指定的初始化程序:init(entity entity: NSEntityDescription,insertIntoManagedObjectContext 上下文:NSManagedObjectContext?).这在 Apple 文档 此处.

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 定义创建的实例,因此只需将其定义为 Course? 类型:

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.

这篇关于解决“无法在 NSManagedObject 类上调用指定的初始化程序"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆