如何将coredata模型转换为Swift结构模型?

我有一个coredata对象(NSManagedObject的子类),我想将它们转换为Model对象,以便我可以重用现有代码。我如何手动映射它们?

模型对象的结构如下: 我已经获取了coredata实体对象。但是现在当我试图将它们映射到下面的视频结构时。 let video:视频=视频(来自:) 我应该在解码器中传递什么?

struct Video: Decodable{
     var id : Int?
      var name : String?
      var video_description : String?
      var thumbnail_image_url : String?
      var provider_name : String?


    private enum VideoKeys: String,CodingKey {
        case id
        case name
        case video_description = "description"
        case thumbnail_image_url = "poster"
        case provider_details = "custom_fields"
    }

    private enum ProviderKeys : String,CodingKey{
        case provider_name = "provider"
    }

     init(from decoder : Decoder) throws {
        if let videoContainer = try? decoder.container(keyedBy: VideoKeys.self){

            self.id = try videoContainer.decodeIfPresent(Int.self,forKey: .id)
            self.name = try videoContainer.decodeIfPresent(String.self,forKey: .name)

            self.video_description = try videoContainer.decodeIfPresent(String.self,forKey: .video_description)

            self.thumbnail_image_url = try videoContainer.decodeIfPresent(String.self,forKey: .thumbnail_image_url)

            if let providercontainer = try? videoContainer.nestedContainer(keyedBy: ProviderKeys.self,forKey: .provider_details){
                self.provider_name = try providercontainer.decodeIfPresent(String.self,forKey: .provider_name)
            }
        }
    }


}
luoyanzheng 回答:如何将coredata模型转换为Swift结构模型?

暂时没有好的解决方案,如果你有好的解决方案,请发邮件至:iooj@foxmail.com
本文链接:https://www.f2er.com/3150755.html

大家都在问