如何正确格式化CoreData中枚举类型的模型属性?

时间:2019-12-18 01:47:39

标签: swift xcode core-data enums codable

因此,我尝试通过OpenWeather API访问每种情况下具有不同图像的图标 天气,例如晚上,白天,下雪等。

Weather类是NSManagedObject和Codable协议的子类,但是类型enum属性将不被接受。对我来说有点困惑。

如何正确格式化此格式?

import Foundation
import CoreData

@objc(Weather)
public class Weather: NSManagedObject, Codable {

    @NSManaged public var icon: Icon

    enum CodingKeys: String, CodingKey {
        case icon
    }

    public required convenience init(from decoder: Decoder) throws {
           guard
               let contextUserInfoKey = CodingUserInfoKey.context,
               let managedObjectContext = decoder.userInfo[contextUserInfoKey] as? NSManagedObjectContext,
               let entity = NSEntityDescription.entity(forEntityName: "Weather", in: managedObjectContext) else {
                   fatalError("Could not retrieve context")
           }

           self.init(entity: entity, insertInto: managedObjectContext)

           let container = try decoder.container(keyedBy: CodingKeys.self)
           icon = try container.decode(Icon.self, forKey: .icon)
       }

       public func encode(to encoder: Encoder) throws {
           var container = encoder.container(keyedBy: CodingKeys.self)
           try container.encode(icon.self, forKey: .icon)
       }

}
  

在与Weather相同的课程中,我有Icon枚举。

 public enum Icon: Codable {
        // clear sky
        case the01D = "01d"
        case the01N = "01n"

        // few clouds
        case the02D = "02d"
        case the02N = "02n"

        // scattered clouds
        case the03D = "03d"
        case the03N = "03n"

        // broken clouds
        case the04D = "04d"
        case the04N = "04n"

        // shower rain
        case the09D = "09d"
        case the09N = "09n"

        // rain
        case the10D = "10d"
        case the10N = "10n"

        // thunderstorm
        case the11D = "11d"
        case the11N = "11n"

        // snow
        case the13D = "13d"
        case the13N = "13n"

        // mist
        case the50D = "50d"
        case the50N = "50n"
    }

0 个答案:

没有答案