How would I save an object of type DateComponents to a CloudKit field?

情到浓时终转凉″ 提交于 2019-12-13 17:47:28

问题


I am using Swift for an iOS app.

I need to store a DateComponents object as a field in CloudKit.

How would I do that?

So far I think I need to set the CloudKit field to type Bytes, and convert the DateComponents object to a Data object. Looking at the documentation for the Data class, I can't figure out how to initialize the Data object. I have no idea how to use the UnsafeBufferPointer used in one of the initializers.

The following code gives a runtime error:

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

Here's the runtime error message in the debug window:

Could not cast value of type 'NSDateComponents' (0x1d04208c8) to '__C.CKRecordValue' (0x1d0420ab0).

I also need to convert Data to DateComponents. Both Data and DateComponents classes conform to the Codable protocol, which inherits the Decoder protocol. One of DateComponents' initializers is:

init(from: Decoder)

which leads me to suspect there is a way to use that init to convert type Data to DateComponents after I get the Data object from the CloudKit field of type Bytes.

The following code:

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

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

}

generates an error in the Xcode editor which says:

Argument type 'Data' does not conform to expected type 'Decoder'

I thought since both Data and DateComponents conform to Decoder protocol that code would work.


回答1:


It seems you might be over-engineering this a bit. Here are a couple alternatives you could consider:

  • Store the date in a date field on CloudKit and re-parse to date components in your app.
  • Store each date component (year, month, day, etc.) as separate integer fields on CloudKit (or as strings if you want to pre-format them).

Just a thought. Good luck. :)



来源:https://stackoverflow.com/questions/56895587/how-would-i-save-an-object-of-type-datecomponents-to-a-cloudkit-field

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!