【问题标题】:Why does my DateComponents object in iOS not save to or retrieve from CloudKit correctly?为什么我在 iOS 中的 DateComponents 对象不能正确保存到 CloudKit 或从 CloudKit 中检索?
【发布时间】:2019-11-21 17:15:44
【问题描述】:

我正在使用 CloudKit 和 Swift for iOS。

我将 DateComponents 类型的对象保存在 Bytes 类型的 CloudKit 字段中。当我检索对象时,它的值与我最初保存的对象不同。

这是我将对象保存到 CloudKit 的代码:

let unsafePointer: UnsafePointer<DateComponents> = UnsafePointer<DateComponents>(&time)
let unsafeBufferPointer: UnsafeBufferPointer<DateComponents> = UnsafeBufferPointer<DateComponents>(start: unsafePointer, count: 1)
let data: Data = Data(buffer: unsafeBufferPointer)
privateRecord.setObject(data as CKRecordValue?, forKey: DatabaseNameStrings.fieldTime)

这是调试窗口中的打印结果:

time = calendar: gregorian (autoupdatingCurrent) timeZone: America/Chicago (autoupdatingCurrent) 小时: 12 分钟: 0 isLeapMonth: false

这是我从 CloudKit 中检索对象的代码:

if let dataTime = privateRecord.object(forKey: DatabaseNameStrings.fieldTime) as? Data {
    let unsafeMutableBufferPointer: UnsafeMutableBufferPointer<DateComponents> = UnsafeMutableBufferPointer<DateComponents>.allocate(capacity: 1)
    _ = dataTime.copyBytes(to: unsafeMutableBufferPointer)
    print("unsafeMutableBufferPointer.first =", unsafeMutableBufferPointer.first as Any)
    privateTime = unsafeMutableBufferPointer.first
}

这是调试窗口中的打印结果:

unsafeMutableBufferPointer.first = 可选(时代:0 年:0 月:0 日:0 小时:0 分钟:0 秒:0 纳秒:0 工作日:0 工作日序数:0 季度:0 周:0 周:0 年:0 年: 0 isLeapMonth: false )

【问题讨论】:

标签: ios swift nsdata cloudkit nsdatecomponents


【解决方案1】:

试图持久化DateComponents 实例是错误的方法;您无法看到对象的内部结构,并且此结构可能会随着 Swift 或 iOS 更新而改变。

您的假设是您可以绕过DateComponents 的初始化,只需恢复代表其他实例的字节即可;这是一个错误的假设。

DateComponents 实际上是免费桥接到NSDateComponents 的底层实例。

当您调用UnsafeBufferPointer&lt;DateComponents&gt;(start: unsafePointer, count: 1) 时,您正在访问用于访问底层NSDateComponents 实例的Swift 结构。

当您随后尝试重新创建此结构时,该基础对象不存在并且您得到 0。

您应该保存重新创建日期组件所需的特定字段(例如时区、小时等)或保存Date 对象。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-11-15
    • 1970-01-01
    • 2018-01-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-04
    相关资源
    最近更新 更多