保存自定义托管对象的上下文时出现以下错误:
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)
}
}
周->天->作业均符合Codable,并且在保存到Plist时有效。它仅在我尝试保存上下文时崩溃。
答案 0 :(得分:1)
这是是 NSObject
,您必须使其符合NSCoding
协议
public protocol NSCoding {
func encode(with coder: NSCoder)
init?(coder: NSCoder) // NS_DESIGNATED_INITIALIZER
}
答案 1 :(得分:1)
您似乎正在尝试将此类型用作Core Data可转换属性。
核心数据可转换属性必须符合NSCoding
。 Codable
具有相似的名称和相似的用途,但是它们不相同并且彼此不兼容。如果要将此类型与Core Data可转换属性一起使用,则它必须符合NSCoding
。