ios - 为什么我在 iOS 中的 DateComponents 对象不能正确地保存到 CloudKit 或从中检索?

标签 ios swift nsdata cloudkit nsdatecomponents

我正在将 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) hour: 12 minute: 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 = Optional(era: 0 year: 0 month: 0 day: 0 hour: 0 minute: 0 second: 0 nanosecond: 0 weekday: 0 weekdayOrdinal: 0 quarter: 0 weekOfMonth: 0 weekOfYear: 0 yearForWeekOfYear: 0 isLeapMonth: false )

最佳答案

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

您的假设是您可以绕过 DateComponents 的初始化简单地通过恢复代表其他实例的字节;这是一个错误的假设。

DateComponents实际上是免费桥接到 NSDateComponents 的基础实例.

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

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

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

关于ios - 为什么我在 iOS 中的 DateComponents 对象不能正确地保存到 CloudKit 或从中检索?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56998458/

相关文章:

ios - Swift 3 DispatchGroup单次成功DispatchWorkItem

iphone - 事件指示器仅动画一次

ios - 在 `cellForRowAt` 中激活 NSLayoutConstraint 直到滚动后才会呈现

ios - 如何在到达音频结尾之前阻止AVAudioPlayer重复播放?

iphone - UIImagePNGRepresentation() 返回不同的字节

iphone - 更改 UISlider iPhone 时模糊 UIImage

ios - 为 IOS 和 Mac 应用程序保存点播图像的推荐文件夹?

ios - 动画 3D 模型以错误的方式跟随 ARKit Scene 的运动

swift - 如何在类层次结构中应用 Swift 泛型/协议(protocol)?

ios - 从 NSData 创建 ENUM