ios - 无法将 [String] 存储为 Core Data 中的二进制数据
问题描述
我正在尝试使用 Core Data 来存储警报对象,每个对象都有一个通知 Uuid 的字符串数组,这些数组与警报负责的通知相对应。问题是当我像这样保存警报对象时......
private func saveAlarm(alarmToSave: Alarm) {
guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else {
return
}
let managedContext = appDelegate.persistentContainer.viewContext
let entity = NSEntityDescription.entity(forEntityName: "Alarm", in: managedContext)!
let alarmMO = AlarmMO(entity: entity, insertInto: managedContext)
alarmMO.setValue(alarmToSave.alarmTime, forKeyPath: "alarmTime")
alarmMO.setValue(alarmToSave.alarmNumber, forKeyPath: "alarmNumber")
alarmMO.setValue(alarmToSave.alarmIntervalBeginTimeDouble, forKeyPath: "startTimeInterval")
alarmMO.setValue(alarmToSave.alarmIntervalEndTimeDouble, forKeyPath: "endTimeInterval")
alarmMO.setValue(alarmToSave.recurrence.hashValue, forKeyPath: "recurrence")
let arrayAsString: String = alarmToSave.notificationUuids.description
let stringAsData = arrayAsString.data(using: String.Encoding.utf16)
alarmMO.setValue(stringAsData, forKeyPath: "notificationUuids")
if managedContext.hasChanges {
do {
try managedContext.save()
self.alarms.append(alarmMO)
} catch let error as NSError {
print("Could not save alarm to CoreData. \(error), \(error.userInfo)")
}
} else {
os_log("No changes to the context to save", log: OSLog.default, type: .debug)
}
}
然后尝试像这样加载警报...
private func loadAlarms() {
os_log("loadAlarms() called", log: OSLog.default, type: .debug)
guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else {
return
}
let managedContext = appDelegate.persistentContainer.viewContext
let fetchRequest = NSFetchRequest<AlarmMO>(entityName: "Alarm")
do {
if self.alarms.count == 0 {
self.alarms = try managedContext.fetch(fetchRequest)
os_log("Loading %d alarms", log: OSLog.default, type: .debug, self.alarms.count)
} else {
os_log("Didn't need to load alarms", log: OSLog.default, type: .debug)
}
} catch let error as NSError {
print("Could not fetch alarms. \(error), \(error.userInfo)")
}
}
所有其他字段都会被加载,但 notificationUuids 不会。为什么这种将字符串数组转换为二进制数据的方法在 Core Data 中不起作用?我已经尝试了很多东西...
- 将属性类型设置为 Transferable,自定义类设置为 [String],无值转换器
- 将属性类型设置为 Transferable,将自定义类设置为 NSArray,无值转换器
- 下面设置属性类型为Transferable,自定义类为[String],值转换器为StringToDataTransformer
- 将属性类型设置为 Transferable,自定义类设置为 [NSAttributedString],值转换器设置为 AttributedStringToDataTransformer 下面
- 将属性类型设置为Transferable,自定义类设置为[NSString],值转换器设置为NSStringToDataTransformer
- 将属性类型设置为二进制数据
没有任何效果。我在这里很绝望。有什么问题?
解决方案
推荐阅读
- snowflake-cloud-data-platform - 雪花的 Lambda 层函数
- java - 测试类中@BeforeTest方法中的WebDriver对象为null
- javascript - 如何在 vuex 中注册多个插件?
- linux - linux上的Dart / Flutter ffi - 配置CMake的问题
- neural-network - 冻结 TensorFlow2 层
- c++ - '->' 运算符是如何工作的,修改大字符串是否是一个好的实现?
- javascript - 向人员列表发送私人消息
- node.js - Gulp 命令运行永远不会完成
- fdr - FDR4.2.7 无法连接许可证服务器
- python - 自定义损失函数失败,内部有标准损失