How would I save an object of type DateComponents

2019-07-25 21:13发布

问题:

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. :)