在扩展NSManagedObject和Codable

时间:2019-01-15 21:32:09

标签: swift core-data codable

我有一个同时扩展NSManagedObjectCodable的类。通过这个类,我试图将应用程序数据轻松地保存在iphone上,并将其从JSON轻松转换为Swift类对象。

我在课堂上遇到的问题是,在尝试在课堂上编写encode函数时遇到错误:

`Reference to member 'arrayOfStrings' cannot be resolved without a contextual type`. 

我花了一些时间尝试解决此问题,但没有运气找出真正的问题是什么。

问题出在两个属性分别为[String][Int]类型。

我的班级在名为Foo+CoreDataClass.swift的文件中被声明为这样:

import Foundation
import CoreData

@objc(Foo)
public class Foo: NSManagedObject, Codable {
    enum CodingKeys: String, CodingKey {
        case id
        case name
        case arrayOfStrings
        case imageUrl
        case arrayOfInts
    }

    public required convenience init(from decoder: Decoder) throws {
        guard let context = decoder.userInfo[CodingUserInfoKey.context!] as? NSManagedObjectContext else { fatalError("Some fatal error") }
        guard let entity = NSEntityDescription.entity(forEntityName: "MyManagedObject", in: context) else { fatalError() }

        self.init(entity: entity, insertInto: context)
        let container = try decoder.container(keyedBy: CodingKeys.self)
        self.id = try container.decode(Int.self, forKey: CodingKeys.id)
        self.name = try container.decode(String.self, forKey: CodingKeys.name)
        self.arrayOfStrings = try container.decode([String].self, forKey: CodingKeys.arrayOfStrings) as NSObject
        self.imageUrl = try container.decode(String.self, forKey: CodingKeys.imageUrl)
        self.arrayOfInts = try container.decode([Int].self, forKey: CodingKeys.arrayOfInts) as NSObject
    }

    public func encode(to encoder: Encoder) throws {
        var container = encoder.container(keyedBy: CodingKeys.self)
        try container.encode(id, forKey: .id)
        try container.encode(name, forKey: .name)
        try container.encode(arrayOfStrings, forKey: .arrayOfStrings)
        try container.encode(imageUrl, forKey: .imageUrl)
        try container.encode(arrayOfInts, forKey: .arrayOfInts)
    }
}

extension CodingUserInfoKey {
    static let context = CodingUserInfoKey(rawValue: "context")
}  

声明属性的另一个文件是Foo+CoreDataProperties.swift定义如下:

extension Foo {

    @nonobjc public class func fetchRequest() -> NSFetchRequest<Foo> {
        return NSFetchRequest<Foo>(entityName: "Foo")
    }

    @NSManaged public var id: Int
    @NSManaged public var name: String?
    @NSManaged public var imageUrl: String?
    @NSManaged public var arrayOfStrings: NSObject?
    @NSManaged public var arrayOfInts: NSObject?
}

这些文件是在我进入Editor标签并选择Create NSManagedObject Subclass时从xcode中创建的。

在遵循了以下帖子:How to use swift 4 Codable in Core Data?和这些Apple Docs on how to encode custom objects之后,我使Foo中的Foo+CoreDataClass.swift类继承自Codable

是否有人成功地将NSManagedObjectCodable用于具有数组类型的属性? 我试图实现的目标是能够在JSON和CoreData对象之间进行转换。

编辑: 我也遇到了使Date对象正确编码的问题,显示了与上述相同的错误消息。

0 个答案:

没有答案