首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >在Swift中同时实现Codable和NSManagedObject

在Swift中同时实现Codable和NSManagedObject
EN

Stack Overflow用户
提问于 2019-02-28 11:47:45
回答 1查看 1.1K关注 0票数 0

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

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

我不想为一个对象创建两个文件(一个作为可编码的结构,另一个作为NSManagedObject类),然后试图弄清楚如何将一个文件转换为另一个文件。因此,我希望在同一个file...while中实现这两种方法,并且仍然能够使用我的“按值传递”代码。

也许这是不可能的。

编辑

我正在寻找一种比从头开始重建所有数据结构更简单的东西。我知道我必须做一些修改才能使一个可编码的结构与NSManagedObject类兼容。我不想做一个需要我手动输入每个属性的自定义初始化器,因为有数百个这样的属性。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-03-01 07:20:48

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

编辑:

我不知道如何让它工作,所以我使用了以下解决方案:

代码语言:javascript
复制
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
    }
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/54918090

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档