Storing NSAttributedString Core Data

For anyone experiencing this problem I found the easiest solution:

In Core Data add an attribute, let's call it attributedText. Then define its type as Transformable. After you create the .h file, change the data type of attributedText from NSDictionary to NSAttributedString.

Now you can save the NSAttributedString in Core Data with no modification needed.

Recalling it is as easy as going:

myObject.attributedText

which will return your NSAttributedString!

Hope this helps someone.


I was checking the Apple Developer Forums and found a thread almost exactly the same as this question, one person had done this but unfortunately did not share the code. All they said was the following:

"In Core Data i have an transformable in the database and i us my own NSVauleTransformer. This is a subclass of NSValueTransformer and creates an attributed string from the data object and back.

Therefore i created a class called PersistableAttributedString which is NSCoding compliant. This class has a string and an array of attributes and builds the attributed string. I also created a class for the possible text attributes which is NSCoding compliant. Together the string and the attributes are all NSCoding compliant.

The class NSAttributedString is also NSCoding compliant, but the attributes are not, that's the problem."

Hope that might help.