How to save NSAttributedString to CoreData

The attribute should look like this in the data model.

enter image description here

The header file should be modified to match this:

@property (nonatomic, retain) NSAttributedString * attributedText;

That's it. You should be able to persist your attributed string just like any other attributes.

Suppose your entity is Event, and you have an object event of type Event, you can access it as event.attributedText. Here are some sample Swift code:

event.attributedText = NSAttributedString(string: "Hello World")
let attributedString = event.attributedText

Let us know should you prefer the answer in your native language.


In Xcode 10 with automatic code generation this is a lot simpler than the other suggestions.

  1. Open the data model and select the name of the Attribute
  2. Open the Data Model inspector (Command+Option+3)
  3. Set Attribute Type to Transformable
  4. Set Custom Class to NSAttributedString

Screenshot of Xcode attribute inspector

And that's it, now you can just save your data in your Swift code as you'd expect, with no need for modifying generated classes or forced casting, e.g.:

detailItem.content = textView.attributedText