Search code examples
swiftnsattributedstringcloudkitnsmutableattributedstring

Adding NSAttributedString to CloudKit


I need to add some NSAttributedString settings for text to CloudKit container.

In CoreData I'm using Atribute type "Transformable". When I'm trying to add NSAttributedString to CloudKit I have a warning message in my console log:

*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Objects of class NSConcreteMutableAttributedString cannot be set on CKRecord'

Can I transform my NSAttributedString to some type which CloudKit accepts and in which one?


Solution

  • As seen in the documentation for CKRecord, you can only store a limited set of data types. Given the possible types, your best option would be to convert the NSAttributedString to NSData. This can be done using an NSKeyedArchiver. Then when you read the data back from CloudKit, you can convert the NSData back to the original NSAttributedString using NSKeyedUnarchiver.

    Please see https://stackoverflow.com/a/36940864/1226963 for an answer that shows how to go back and forth between NSAttributedString and NSData. (actually that answer uses NSMutableAttributedString). And of course you would put/get the NSData into/from a CKRecord instead of NSUserDefaults.