如何将NSAttributedString保存到CoreData

li *_*ing 7 core-data uitextview nsattributedstring ios swift

我想保存我的UItextview'text的attributedString.我试图转换为字符串并保存.但是当我回到设置text'attributedString时,它不起作用.

这是我转换为String的方式:

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

这是我回到设置的方式:

text.attributedText = NSAttributedString(string: size)
Run Code Online (Sandbox Code Playgroud)

但是我的TextView只显示了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";
}
Run Code Online (Sandbox Code Playgroud)

对不起,我无法发布图片.我使用swift来做到这一点.

我的问题:我怎么能这样做?或者有另一种方法来保存attributedText?

Joe*_*ith 9

该属性在数据模型中应如下所示.

在此输入图像描述

应修改头文件以匹配此:

@property (nonatomic, retain) NSAttributedString * attributedText;
Run Code Online (Sandbox Code Playgroud)

而已.您应该能够像任何其他属性一样保留您的属性字符串.

假设您的实体是Event,并且您有一个Event类型的对象事件,您可以将其作为event.attributedText访问.以下是一些示例Swift代码:

event.attributedText = NSAttributedString(string: "Hello World")
let attributedString = event.attributedText
Run Code Online (Sandbox Code Playgroud)

如果您更喜欢您的母语,请告诉我们.


rod*_*han 8

在具有自动代码生成功能的 Xcode 10 中,这比其他建议简单得多。

  1. 打开数据模型并选择属性的名称
  2. 打开数据模型检查器(Command+ Option+ 3
  3. 设置Attribute TypeTransformable
  4. 设置Custom ClassNSAttributedString

Xcode 属性检查器的屏幕截图

就是这样,现在您可以按照预期将数据保存在 Swift 代码中,无需修改生成的类或强制转换,例如:

detailItem.content = textView.attributedText