在保存自定义托管对象的上下文时,我得到了以下错误:
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)我使用NSManagedObject的自定义子类来表示"Week“实体。Week实体中充满了Day对象,根据错误,这些对象似乎是问题所在:
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)
    }
}周->日->作业都符合可编码的,并且在保存到Plist时可以工作。只有当我试图保存上下文时,它才会崩溃。
发布于 2020-05-11 04:03:44
这是一个NSObject,你必须使它符合NSCoding协议。
public protocol NSCoding {
    func encode(with coder: NSCoder)
    init?(coder: NSCoder) // NS_DESIGNATED_INITIALIZER
}https://stackoverflow.com/questions/61720730
复制相似问题