Resolving'无法调用NSManagedObject类上的指定初始化器' [英] Resolving 'Failed to call designated initializer on NSManagedObject class'

查看:292
本文介绍了Resolving'无法调用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 课程,它还使用标准创建课程实体的实例> init 方法。这是明确不允许的:你必须使用指定的初始化: init(entity entity:NSEntityDescription,
insertIntoManagedObjectContext context: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定义创建的实例,所以只需将它定义为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屋!

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