core-datacloudkitckrecordtransformable

How to decode a CKRecord NSData field, created by a transformable CoreData attribute, back to its original type?


Setup:

My app uses CoreData & CloudKit sync.
Entity Item has among others an attribute status of type Int16 with corresponding property @NSManaged var status: Int16, and an attribute names of type transformable using NSSecureUnarchiveFromDataTransformer with corresponding property @NSManaged var names: Set<String>?

To get notified when iCloud records change, the app uses a query subscription.
When a notification is delivered, an identifier of the changed object is sent, the objectID of the NSManagedObject is obtained, and the corresponding ckRecord: CKRecord is fetched using persistentContainer.record(for: objectID) of persistentContainer: NSPersistentCloudKitContainer to get the actual property values.

Question:

"normal" field values, e.g. status, can easily be obtained using ckRecord["CD_status"] as! Int16. I can also get ckRecord["CD_names"] as! NSData, but I don't know how to convert it back to Set<String>?.


Solution

  • Types for properties are limited to some types in CoreData, Set<String> not being one, that's why you need a transformer, that will transform it into (NS)Data.

    So, you could use that transformer to transform it back with transformedValue(_:):

    NSSecureUnarchiveFromDataTransformer().transformedValue(ckRecord["CD_names"])