CoreData:错误:无法在NSManagedObject自定义类上调用指定的初始化程序 [英] CoreData: error: Failed to call designated initializer on NSManagedObject custom class

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

问题描述

当我调用函数CacheStation时,出现错误:CoreData:错误:无法在NSManagedObject类SaveModel上调用指定的初始化程序。没什么,没少。如何解决此问题?

When I call the function CacheStation I get the error: CoreData: error: Failed to call designated initializer on NSManagedObject class SaveModel. Nothing more nothing less. How can I resolve this issue?

SaveModel.swift:

SaveModel.swift:

import Foundation
    import CoreData
    import UIKit

class SaveModel: NSManagedObject {

    func CacheStations(){
        // create an instance of our managedObjectContext
        let moc = (UIApplication.sharedApplication().delegate as! AppDelegate).managedObjectContext

        // we set up our entity by selecting the entity and context that we're targeting
        let entity = NSEntityDescription.insertNewObjectForEntityForName("CachedStations", inManagedObjectContext: moc) as! SaveModel

        //add the data
        entity.land = "nl";

        // we save our entity
        do {
            try moc.save()
        } catch {
            fatalError("Failure to save context: \(error)")
        }
}

SaveModel + CoreDataProperties.swift :

SaveModel+CoreDataProperties.swift:

import Foundation
import CoreData

extension SaveModel {
    @NSManaged var land: String?
}

我称之为CacheStation的位置:

Where I call CacheStations:

import UIKit

class ViewController: UIViewController {

    @IBAction func saveShizzle(sender: AnyObject) {
        let sm = SaveModel();
        sm.CacheStations();
    }
}


推荐答案

此行:

let sm = SaveModel();

使用标准的 init()方法创建 SaveModel 的实例,但是 NSManagedObjects 必须使用指定的初始化程序进行初始化:

uses the standard init() method to create an instance of SaveModel, but NSManagedObjects must be initialised using the designated initialiser:

init(entity entity: NSEntityDescription, insertIntoManagedObjectContext context: NSManagedObjectContext?)

(或像在CacheStations方法中那样,使用 NSEntityDescription.insertNewObjectForEntityForName(_,inManagedObjectContext:moc)进行调用

(or, as in your CacheStations method, using NSEntityDescription.insertNewObjectForEntityForName(_, inManagedObjectContext: moc) which calls the designated initialiser).

因为似乎创建了 sm 只是为了拥有要调用<$的实例c $ c> CacheStations ,我将该方法更改为类方法:

Since it seems sm is created only to have an instance on which to call CacheStations, I would change that method to a class method:

class func CacheStations(){

并更改您的 saveShizzle 方法使用类方法:

and change your saveShizzle method to use the class method:

@IBAction func saveShizzle(sender: AnyObject) {
    SaveModel.CacheStations();
}

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

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