Home > Software engineering >  CoreData Entity to Model
CoreData Entity to Model

Time:02-20

I do get a JSON and parse it to my model. In order to use this data while I am offline, I do store it using Core Data. For this, I created an entity and insert it the following way:

   taskEntity.id = Int32(task.id ?? 0)
   taskEntity.name = task.name...
   try context.save()

My question is, what is the best way to convert this entity back to my model in order to use it later in my code to handle the offline case? Create each object one by one as I do to store the data, or there is a more elegant way to do it? Thanks.

CodePudding user response:

I would create an init in the model type that takes an entity object as argument

init(_ entity: MyEntity) {
    self.id = entity.id
    self.name = entity.name
}

Then you can use a fetch request to get all entity objects and use map to convert it directly into model objects

Something like

let modelObjects = MyEntity.fetchAll().map(\.MyModel.init)
  • Related