I'm getting the following error when saving the context of a custom managed object:
2020-05-10 20:43:40.432001-0400 Timecard[26285:12499267] [error] error: SQLCore dispatchRequest: exception handling request: <NSSQLSaveChangesRequestContext: 0x280c206c0> ,
-[Timecard.Day encodeWithCoder:]: unrecognized selector sent to instance 0x281a0c460 with userInfo of (null)
I use a custom subclass of NSManagedObject to represent the "Week" entity. The Week entity is full of Day objects, which according to the error, seems to be where the issue is:
import Foundation
public class Day: NSObject, ObservableObject, Codable {
var name: String
@Published var date: Date
@Published var jobs: [Job] = []
var totalHours: Double {
get {
var totalHours = 0.0
for job in jobs {
totalHours = totalHours + job.totalHours
}
return totalHours
}
}
var totalDollars: Double {
get {
var totalDollars = 0.0
for job in jobs {
totalDollars = totalDollars + job.totalDollars
}
return totalDollars
}
}
init(name: String, date: Date) {
self.name = name
self.date = date
}
init(name: String) {
self.name = name
self.date = Date()
}
func add(job: Job) {
jobs.append(job)
}
// Mark: - Codable Encoding & Decoding
enum CodingKeys: String, CodingKey {
case date
case jobs
case name
}
required public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
name = try container.decode(String.self, forKey: .name)
date = try container.decode(Date.self, forKey: .date)
jobs = try container.decode([Job].self, forKey: .jobs)
}
public func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(name, forKey: .name)
try container.encode(date, forKey: .date)
try container.encode(jobs, forKey: .jobs)
}
}
Week -> Day -> Job all conform to Codable and it works when saving to a Plist. It only crashes when I try to save the context.