保存上下文时核心数据编码崩溃

问题描述 投票:0回答:1

保存自定义托管对象的上下文时出现以下错误:

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

Week-> Day-> Job全部符合Codable,并且在保存到Plist时有效。它仅在我尝试保存上下文时崩溃。

swift core-data swiftui nsmanagedobject codable
1个回答
0
投票

它是is-a NSObject,必须使其符合NSCoding协议

public protocol NSCoding {
    func encode(with coder: NSCoder)
    init?(coder: NSCoder) // NS_DESIGNATED_INITIALIZER
}
© www.soinside.com 2019 - 2024. All rights reserved.