在Swift中同时实现Codable和NSManagedObject

问题描述 投票:0回答:1

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

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

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

也许这是不可能的。

编辑

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

swift swift4 nsmanagedobject codable nscopying
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
    }
}
最新问题
© www.soinside.com 2019 - 2024. All rights reserved.