swift - 如何正确格式化 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"
}
解决方案
推荐阅读
- javascript - 如何为 vim 命令执行 tern?
- neo4j - 如何将查询中的所有节点精确匹配到另一个
- c# - 通过 C# 添加 SQL 参数不起作用,但在存储过程中进行硬编码可以吗?
- angular - 将页面选择设置为 PrimeNG p-table 的最后一页
- css - SCSS 映射值内的逗号(框阴影)
- c# - IEqualityComparer 错误
- php - 在 Laravel 中路由锚标记的最佳方法
- react-native - 如何创建用户最后一次在线的“最后一次看到”时间?
- python - 我怎样才能刮掉所有击球手的名字?
- vba - 使用 Windows 10 将 Excel 范围粘贴到 2016 年的 PowerPoint 幻灯片