在 Swift 中同时实现 Codable 和 NSManagedObject

Implementing Codable and NSManagedObject simultaneously in Swift

我有一个订单处理应用程序正在为我的雇主工作,该应用程序最初设计用于从 API 动态获取有关订单、产品和客户的所有数据。因此,所有对象和处理这些对象的所有函数都在应用程序中以 "pass by value" 期望进行交互,利用符合 Codable 的结构。

我现在必须缓存几乎所有这些对象。输入 CoreData。

我不想为一个对象创建两个文件(一个作为 Codable 结构,另一个作为 NSManagedObject class),然后试图找出如何将一个转换为另一个。所以我想在同一个文件中实现两者......同时仍然能够以某种方式使用我的 "pass by value" 代码。

也许这是不可能的。

编辑

我正在寻找比从头开始重建所有数据结构更简单的方法。我知道我必须做一些改动才能使 Codable 结构与 NSManagedObject class 兼容。我想避免制作需要我手动输入每个 属性 的自定义初始化程序,因为它们有数百个。

最后,从没有缓存的 API 动态应用程序迁移到缓存应用程序时,听起来没有 "good" 解决方案。

我决定硬着头皮试试这个问题中的方法:

编辑:

我不知道该怎么做,所以我使用了以下解决方案:

import Foundation
import CoreData

/*
 SomeItemData vs SomeItem:
 The object with 'Data' appended to the name will always be the codable struct. The other will be the NSManagedObject class.
 */

struct OrderData: Codable, CodingKeyed, PropertyLoopable
{
    typealias CodingKeys = CodableKeys.OrderData

    let writer: String,
    userID: String,
    orderType: String,
    shipping: ShippingAddressData
    var items: [OrderedProductData]
    let totals: PaymentTotalData,
    discount: Float

    init(json:[String:Any])
    {
        writer = json[CodingKeys.writer.rawValue] as! String
        userID = json[CodingKeys.userID.rawValue] as! String
        orderType = json[CodingKeys.orderType.rawValue] as! String
        shipping = json[CodingKeys.shipping.rawValue] as! ShippingAddressData
        items = json[CodingKeys.items.rawValue] as! [OrderedProductData]
        totals = json[CodingKeys.totals.rawValue] as! PaymentTotalData
        discount = json[CodingKeys.discount.rawValue] as! Float
    }
}

extension Order: PropertyLoopable //this is the NSManagedObject. PropertyLoopable has a default implementation that uses Mirror to convert all the properties into a dictionary I can iterate through, which I can then pass directly to the JSON constructor above
{
    convenience init(from codableObject: OrderData)
    {
        self.init(context: PersistenceManager.shared.context)

        writer = codableObject.writer
        userID = codableObject.userID
        orderType = codableObject.orderType
        shipping = ShippingAddress(from: codableObject.shipping)
        items = []
        for item in codableObject.items
        {
            self.addToItems(OrderedProduct(from: item))
        }
        totals = PaymentTotal(from: codableObject.totals)
        discount = codableObject.discount
    }
}