0

I know how to do it when decoding which is stated below, but how would I go about it for encoding ?

Just need to look at weatherDetail: NSSet I deleted the other containers as it's not necessary for the example.

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

Here I've done it wrong, but was wondering how I could figure this out.

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

1 Answers1

1

I found a solution for this, actually it's pretty simple. What you need to do is:

  1. Convert your NSSet to Array of WeatherDetail
  2. Encode the array

In you example this would be:

var container = encoder.container(keyedBy: CodingKeys.self)
let weatherDetailArray = self.weatherDetail.allObjects as? [WeatherDetail]    
try container.encode(weatherDetailArray, forKey: . weatherDetail)
Allinone51
  • 624
  • 1
  • 7
  • 19