首页 > 解决方案 > 如何正确格式化 CoreData 中枚举类型的模型属性?

问题描述

所以我试图从 OpenWeather API 访问图标,这些图标对于每种天气情况都有不同的图像,例如夜晚、白天、雪地等。

Weather 类是 NSManagedObject 和 Codable 协议的子类,但不会接受 type 枚举属性。这对我来说有点困惑。

正确格式化的方法是什么?

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"
    }

标签: swiftxcodecore-dataenumscodable

解决方案


推荐阅读