【问题标题】:How would I save an object of type DateComponents to a CloudKit field?如何将 DateComponents 类型的对象保存到 CloudKit 字段?
【发布时间】:2019-11-15 15:31:42
【问题描述】:

我正在将 Swift 用于 iOS 应用程序。

我需要将 DateComponents 对象作为字段存储在 CloudKit 中。

我该怎么做?

到目前为止,我认为我需要将 CloudKit 字段设置为 Bytes 类型,并将 DateComponents 对象转换为 Data 对象。查看 Data 类的文档,我不知道如何初始化 Data 对象。我不知道如何使用其中一个初始化程序中使用的 UnsafeBufferPointer。

以下代码给出了运行时错误:

newRecord.setObject((dateComponents as! __CKRecordObjCValue), forKey: DatabaseNameStrings.fieldTime)

这是调试窗口中的运行时错误消息:

无法将“NSDateComponents”(0x1d04208c8) 类型的值转换为“__C.CKRecordValue”(0x1d0420ab0)。

我还需要将 Data 转换为 DateComponents。 Data 和 DateComponents 类都符合 Codable 协议,该协议继承了 Decoder 协议。 DateComponents 的初始化器之一是:

init(from: Decoder)

这让我怀疑在我从 Bytes 类型的 CloudKit 字段中获取 Data 对象后,有一种方法可以使用该 init 将类型 Data 转换为 DateComponents。

以下代码:

if let data = privateRecord.object(forKey: DatabaseNameStrings.fieldTime) as? Data {

    let dateComponents = DateComponents(from: data) // error here

}

在 Xcode 编辑器中生成一个错误:

参数类型“数据”不符合预期类型“解码器”

我认为由于 Data 和 DateComponents 都符合解码器协议,因此代码可以工作。

【问题讨论】:

    标签: field nsdata cloudkit nsdatecomponents ckrecord


    【解决方案1】:

    看来你可能有点过度设计了。您可以考虑以下几种选择:

    • 将日期存储在 CloudKit 的日期字段中,然后重新解析为应用中的日期组件。
    • 将每个日期组件(年、月、日等)存储为 CloudKit 上的单独整数字段(或者如果您想对其进行预格式化,则存储为字符串)。

    只是一个想法。祝你好运。 :)

    【讨论】:

      猜你喜欢
      • 2019-11-21
      • 1970-01-01
      • 1970-01-01
      • 2020-08-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多