我知道在解码时该怎么做,如下所述,但是我将如何进行编码呢?
只需要查看weatherDetail: NSSet我删除了其他容器,因为示例不需要。
public class CurrentWeather: NSManagedObject, Codable {
@NSManaged public var weatherCoordinate: WeatherCoordinate?
@NSManaged public var weatherDetail: NSSet
@NSManaged public var temperatureDescription: TemperatureDescription
@NSManaged public var locationName: String
@NSManaged public var date: Int32
enum CodingKeys: String, CodingKey {
case weatherCoordinate = "coord"
case weatherDetail = "weather"
case temperatureDescription = "main"
case locationName = "name"
case date = "dt"
}
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: "CurrentWeather", in: managedObjectContext) else {
fatalError("Could not retrieve context")
}
self.init(entity: entity, insertInto: managedObjectContext)
let container = try decoder.container(keyedBy: CodingKeys.self)
weatherDetail = NSSet(array: try container.decode([WeatherDetail].self, forKey: .weatherDetail))
}
在这里我做错了,但想知道我怎么能解决这个问题。
public func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
// NSSet(array: try container.encode(weatherDetail.self, forKey: .weatherDetail)) }