I've been able to find multiple articles about codable in core data and decoding JSON. But I'm struggling when a to-many relationship exists. I currently have the following which works, but how do I filter the JSON based on an attribute in the child?
Checklist entity (Checklist <--->> TestGroup, relationship called hasTestGroups)
required convenience public init(from decoder: Decoder) throws {
guard let contextUserInfoKey = CodingUserInfoKey.context,
let managedObjectContext = decoder.userInfo[contextUserInfoKey] as? NSManagedObjectContext,
let entity = NSEntityDescription.entity(forEntityName: "Checklist", in: managedObjectContext) else {fatalError("Failed to decode Checklist")}
self.init(entity: entity, insertInto: managedObjectContext)
let values = try decoder.container(keyedBy: CodingKeys.self)
do {
name = try values.decode(String?.self, forKey: .name)
hasTestGroups = NSSet(array: try values.decode([TestGroup].self, forKey: .hasTestGroups))
} catch {
print("decoding error")
}
}
Then in a view where I decode the JSON:
guard let url = Bundle.main.url(forResource: "masterdatabase", withExtension: "json") else {fatalError("no file")}
do {
let json = try Data(contentsOf: url)
let decoder = JSONDecoder()
decoder.userInfo[CodingUserInfoKey.context!] = self.moc
do {
let subjects = try decoder.decode([Checklist].self, from: json)
subjects.first?.name = self.desiredChecklistName
subjects.first?.eventNumber = Int32(self.desiredChecklistNumber)!
subjects.first?.eventDate = self.desiredChecklistData
How do I filter the JSON on decode based on something like TestGroup.name? It's a NSSet, so .filter{$0...} doesn't work.