我正在为我的雇主开发一个订单处理应用程序,该应用程序最初设计用于从API动态获取有关订单、产品和客户的所有数据。因此,所有的对象和所有处理这些对象的函数都在应用程序中以“按值传递”的期望进行交互,利用符合Codable的结构。
我现在必须缓存几乎所有这些对象。输入CoreData。
我不想为一个对象创建两个文件(一个作为可编码的结构,另一个作为NSManagedObject类),然后试图弄清楚如何将一个文件转换为另一个文件。因此,我希望在同一个file...while中实现这两种方法,并且仍然能够使用我的“按值传递”代码。
也许这是不可能的。
编辑
我正在寻找一种比从头开始重建所有数据结构更简单的东西。我知道我必须做一些修改才能使一个可编码的结构与NSManagedObject类兼容。我不想做一个需要我手动输入每个属性的自定义初始化器,因为有数百个这样的属性。
发布于 2019-03-01 07:20:48
最后,在没有缓存的情况下从API动态应用程序迁移到缓存应用程序时,听起来似乎没有“好”的解决方案。
编辑:
我不知道如何让它工作,所以我使用了以下解决方案:
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
}
}
https://stackoverflow.com/questions/54918090
复制相似问题