0

我正在为我的雇主开发一个订单处理应用程序,该应用程序最初旨在从 API 动态获取有关订单、产品和客户的所有数据。因此,所有对象以及处理这些对象的所有函数都在应用程序中以“按值传递”的期望进行交互,使用符合 Codable 的结构。

我现在必须缓存几乎所有这些对象。输入核心数据。

我不想为一个对象创建两个文件(一个作为 Codable 结构,另一个作为 NSManagedObject 类),然后试图弄清楚如何将一个文件转换为另一个文件。所以我想在同一个文件中实现两者......同时仍然能够以某种方式使用我的“按值传递”代码。

也许这是不可能的。

编辑

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

4

1 回答 1

1

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

我决定硬着头皮试试这个问题中的方法:How to use swift 4 Codable in Core Data?

编辑:

我不知道如何做到这一点,所以我使用了以下解决方案:

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
    }
}
于 2019-02-28T23:20:48.077 回答