li fubing
li fubing

Reputation: 113

How to save NSAttributedString to CoreData

I want to save the attributedString of my UItextview'text. I tried to convert to string and save. But when I back to set the text'attributedString,it not work.

This is how I convert to String:

var a = String(stringInterpolationSegment: text.attributedText)
    Data.setValue(a, forKey: "font")
    Data.managedObjectContext?.save(nil)

This is how I back to set:

text.attributedText = NSAttributedString(string: size)

but my TextView just show the AttributedSting

{
NSFont = "<UICTFont: 0x7fa9fa82aec0> font-family: \"Helvetica Neue\"; font-weight: normal; font-style: normal; font-size: 18.00pt";
NSParagraphStyle = "Alignment 0, LineSpacing 0, ParagraphSpacing 0, ParagraphSpacingBefore 0, HeadIndent 0, TailIndent 0, FirstLineHeadIndent 0, LineHeight 0/0, LineHeightMultiple 0, LineBreakMode 0, Tabs (\n    28L,\n    56L,\n    84L,\n    112L,\n    140L,\n    168L,\n    196L,\n    224L,\n    252L,\n    280L,\n    308L,\n    336L\n), DefaultTabInterval 0, Blocks (null), Lists (null), BaseWritingDirection -1, HyphenationFactor 0, TighteningFactor 0, HeaderLevel 0";
}

I'm sorry that I can't post images. I use the swift to do this.

My questions: How can i do this ? Or there have another way to save the attributedText?

Upvotes: 11

Views: 6474

Answers (3)

rodhan
rodhan

Reputation: 643

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

Upvotes: 9

Joe Smith
Joe Smith

Reputation: 1920

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.

Upvotes: 14

Rashad
Rashad

Reputation: 11197

Yes you can add attributedText with a simple workaround.

Add a attribute of type Transformable. After creating the .h file change the type of that attribute to NSAttributedString. In that attribute you can easily save the attributed string.

Hope this helps.. :)

Upvotes: 0

Related Questions