简体   繁体   English

根据模型类获取 CoreData 实体,而不是创建单独的 NSManaged 子类

[英]Fetch CoreData entity as per Model class and not create separate NSManaged subclass

Let's say I have a model like below假设我有一个像下面这样的模型

class Employee: Codable {    
    var id: String?
    var personalDetails: Person?
}

class Person: Codable {
    var firstName:String?
    var lastName: String?
}

Now I have to maintain an Entity (say DBEmployee) inside CoreData which will have the exact same properties现在我必须在CoreData 中维护一个具有完全相同属性的实体(比如 DBEmployee)

Now, is there a way to NOT create a separate NSManaged subclass(DBEmployee) for that entity which will have the same properties(as Employee) and have that entity extract it's properties as per the properties of Employee现在,有没有办法创建一个单独的NSManaged该实体将拥有相同的属性(如员工)的子类(DBEmployee),并有实体提取它的属性,每属性Employee

My main problem is when I create my CoreData operations for fetch, it returns me DBEmployee which I then have to convert to Employee which has exactly the same properties (because the method that uses this fetch accepts Employee as the parameter and not DBEmployee)我的主要问题是,当我为 fetch 创建 CoreData 操作时,它返回我DBEmployee然后我必须将其转换为具有完全相同属性的Employee (因为使用此 fetch 的方法接受 Employee 作为参数而不是 DBEmployee)

You can get values back as either a NSManaged object / subclass or a dictionary of [String:Any] depending on the fetch result type.您可以根据获取结果类型将值作为 NSManaged 对象/子类或 [String:Any] 字典取回。 However, neither of those is a POSO (plain old Swift object.)但是,这些都不是 POSO(普通的旧 Swift 对象。)

Since they both have the exact same properties, can you can change the method / API to take a protocol instead?由于它们都具有完全相同的属性,您可以更改方法/API 以采用协议吗?

It really comes down to if the API really needs a Codable model (because it's going to serialize it, for example) or if you can change the method (or possibly add to it)这真的归结为 API 是否真的需要一个 Codable 模型(因为它会序列化它,例如)或者您是否可以更改方法(或可能添加到其中)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM