CoreData NSManagedObject& JSON可编码无法正常工作 [英] CoreData NSManagedObject & JSON Encodable not working

查看:59
本文介绍了CoreData NSManagedObject& JSON可编码无法正常工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在iOS 13.1上创建一个既符合 Encodable 又符合 NSManagedObject 的对象类。 .2和Swift 4.2。这是我的课程:

I am trying to create an object class which is both a class conforming Encodable and NSManagedObject, on iOS 13.1.2 and Swift 4.2. This is my class:

import CoreData

class Test: NSManagedObject, Decodable {
    @NSManaged var name: String?

    enum CodingKeys: String, CodingKey {
        case name
    }

    required convenience init(from decoder: Decoder) throws {
        let managedContext = AppDelegate.persistentContainer.viewContext

        guard let entity = NSEntityDescription.entity(forEntityName: "TestEntity", in: managedContext) else { fatalError() }

        self.init(entity: entity, insertInto: managedContext)

        let values = try decoder.container(keyedBy: CodingKeys.self)
        name = try values.decodeIfPresent(String.self, forKey: .name)
    }
}

我的数据模型:

My data model:

和我在AppDelegate中的persistentContainer:

And my persistentContainer in AppDelegate:

static var persistentContainer: NSPersistentContainer = {
    let container = NSPersistentContainer(name: "testContainer")
    container.loadPersistentStores(completionHandler: { (storeDescription, error) in
        if let error = error as NSError? {
            fatalError("Unresolved error \(error), \(error.userInfo)")
        }
    })
    return container
}()

我使用此方法创建我的 Test 类:

I use this method to create a new instance of my Test class:

do {
    let test = try JSONDecoder().decode(Test.self, from: "{\"name\":\"Test\"}".data(using: .utf8)!)
    print(test.name)
} catch let error {
    print(error)
}

但这给了我以下错误: / p>

But this gives me the following error:

valueNotFound(Test.Test, Swift.DecodingError.Context(codingPath: [], debugDescription: "The given data did not contain a top-level value.", underlyingError: nil))

我在这里做什么错了?

What am I doing wrong here?

推荐答案

我终于使它起作用了。发生这种情况是因为我使用的是一个单独的模型,该模型是按照NSManagedObject和Decodable制作的,就像OP的Test类一样。答案在这里使我成为其中的一部分,但是我所缺少的是,我没有使用单独的模型必须修改生成的实体类以使其符合Decodable并将其用作我的可编码模型。

I finally got this to work. This happened to me because I was using a separate model that I made to conform to NSManagedObject and Decodable, much like the OP's Test class. The answer here got me part of the way there, but what I was missing is that instead of using a separate model, I had to modify the generated entity class to conform to Decodable and use that as my codable model.

因此,在将Codegen更改为Manual并创建NSManagedObject类(如上面的链接所述)之后,您的类文件中的 Test + CoreDataClass.swift 变为:

So after changing the Codegen to Manual and creating the NSManagedObject class like the link above mentions, your class in the file Test+CoreDataClass.swift becomes this:

import CoreData

@objc(Test)
public class Test: NSManagedObject, Decodable {
    @NSManaged var name: String?

    enum CodingKeys: String, CodingKey {
        case name
    }

    required convenience init(from decoder: Decoder) throws {
        let managedContext = AppDelegate.persistentContainer.viewContext

        guard let entity = NSEntityDescription.entity(forEntityName: "TestEntity", in: managedContext) else { fatalError() }

        self.init(entity: entity, insertInto: managedContext)

        let values = try decoder.container(keyedBy: CodingKeys.self)
        name = try values.decodeIfPresent(String.self, forKey: .name)
    }
}

这篇关于CoreData NSManagedObject& JSON可编码无法正常工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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