0

我知道在解码时该怎么做,如下所述,但是我将如何进行编码呢?

只需要查看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))        }
4

1 回答 1

0

我找到了一个解决方案,实际上它非常简单。你需要做的是:

  1. 将您的 NSSet 转换为 WeatherDetail 数组
  2. 编码数组

在您的示例中,这将是:

var container = encoder.container(keyedBy: CodingKeys.self)
let weatherDetailArray = self.weatherDetail.allObjects as? [WeatherDetail]    
try container.encode(weatherDetailArray, forKey: . weatherDetail)
于 2020-04-23T13:21:23.773 回答