Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 771
li fubing Avatar asked May 20 '15 01:05

li fubing


2 Answers

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

like image 91
rodhan Avatar answered Nov 16 '22 18:11

rodhan


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.

like image 23
Joe Smith Avatar answered Nov 16 '22 19:11

Joe Smith