如何将NSAttributedString保存到CoreData

时间:2015-05-20 01:36:05

标签: ios swift core-data uitextview nsattributedstring

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

这是我转换为String的方式:

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

这是我回到设定的方式:

text.attributedText = NSAttributedString(string: size)

但我的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";
}

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

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

3 个答案:

答案 0 :(得分:9)

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

enter image description here

应修改头文件以匹配:

@property (nonatomic, retain) NSAttributedString * attributedText;

那就是它。您应该能够像任何其他属性一样保留您的属性字符串。

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

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

如果您更喜欢您的母语答案,请告诉我们。

答案 1 :(得分:0)

是的,您可以使用简单的解决方法添加attributedText。

添加Transformable类型的属性。创建.h文件后,将该属性的类型更改为NSAttributedString。在该属性中,您可以轻松保存属性字符串。

希望这会有所帮助.. :)

答案 2 :(得分:0)

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

  1. 打开数据模型并选择属性名称
  2. 打开数据模型检查器(命令 + 选项 + 3
  3. Attribute Type设置为Transformable
  4. Custom Class设置为NSAttributedString

Screenshot of Xcode attribute inspector

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

detailItem.content = textView.attributedText