首页 > 解决方案 > 无法将 [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 中不起作用?我已经尝试了很多东西...

没有任何效果。我在这里很绝望。有什么问题?

标签: iosarraysswiftcore-datapersistence

解决方案


推荐阅读