swift - 保存上下文时核心数据编码崩溃
问题描述
保存自定义托管对象的上下文时出现以下错误:
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 实体充满了 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 时可以使用。只有当我尝试保存上下文时它才会崩溃。
解决方案
It is is-a NSObject
, you have to conform it to NSCoding
protocol
public protocol NSCoding {
func encode(with coder: NSCoder)
init?(coder: NSCoder) // NS_DESIGNATED_INITIALIZER
}
推荐阅读
- java - 如何在基于 Spring 的 REST API 中将路径参数映射到 gRPC 对象?
- reactjs - 在组件中引用另一个组件时遇到问题
- sql - 左外连接中的无效操作(在 Access 中)
- .htaccess - .htaccess 将所有请求重定向到 /home/aaa/public_html 到 /home/bbb/public_html?
- vba - “错误 -2147188160 (80048240) 形状(未知成员):无效请求。” 尝试在 PowerPoint 中将对象转换为图像时
- bash - bash 等效于 tcsh 修饰符,用于提取路径组件
- ios - “StorageMetadata”没有成员“downloadURL”
- mysql - SQL Server 中的 MySQL INDEX() 语法等效
- ios - 如何在 SharkORM 中使用填充的 SQLite 数据库
- r - 基于数据框中多列的查找值