无法将[String]作为二进制数据存储在Core Data中

时间:2018-12-03 02:04:02

标签: ios arrays swift core-data persistence

我正在尝试使用Core Data存储Alarm对象,每个对象都有一个NotificationUuids的String数组,这些数组对应于警报所负责的通知。问题是当我像这样保存警报对象时...

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不会加载。为什么这种将String数组转换为二进制数据的方法在Core Data中不起作用?我已经尝试了很多东西...

  • 将属性类型设置为“可转移”,将自定义类设置为“ [字符串]”, 没有价值转换器
  • 将“属性类型”设置为“可转移”, 自定义类到NSArray,没有值转换器
  • 设置属性 类型为Transferable,自定义类为[String],值转换器为 下面的StringToDataTransformer
  • 将属性类型设置为 可将自定义类传输到[NSAttributedString],值转换器 到
  • 下的AttributedStringToDataTransformer
  • 设置属性类型 到可转让,自定义类到[NSString],值转换器 下面的NSStringToDataTransformer
  • 将属性类型设置为二进制数据

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

0 个答案:

没有答案