如何将NSAttributedString保存到CoreData

11
我想保存UITextview文本的attributedString。我试图将其转换为字符串并保存。但是,当我回来设置text的attributedString时,它不起作用。
这是我如何转换为字符串:
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来完成这个操作。

我的问题是:我该怎么做?还有其他方法可以保存attributedText吗?


可能是Storing NSAttributedString Core Data的重复问题。 - i_am_jorf
@i_am_jorf,我之前看过这个问题,它是用Objective-C编写的。我还不知道如何解决。 - li fubing
请参考 i_am_jorf 发布的链接中 pob21 给出的答案。虽然它不是被接受的答案,但这是正确的做法。我在我的应用程序中也是这样操作的(使用 Swift)。 - Joe Smith
@JoeSmith感谢您的建议!很抱歉我要问一个类似的问题。我只是一个Swift初学者。如果您不介意,可以分享一下您的代码吗?谢谢。 - li fubing
3个回答

14

在数据模型中,该属性应该看起来像这样。

enter image description here

头文件应该被修改以匹配此内容:

@property (nonatomic, retain) NSAttributedString * attributedText;

就是这样,您应该能够像处理其他属性一样持久保存所设置的字符串。

假设实体名为Event,有一个类型为Event的事件对象,你可以通过event.attributedText进行访问。以下是一些Swift代码示例:

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

如果您希望用您的母语回答,请告诉我们。


谢谢您的建议!我对您所说的头文件该如何处理感到困惑。我是Swift初学者,希望能得到您的慷慨帮助。 :-) - li fubing

9
在 Xcode 10 中,使用自动代码生成比其他建议要简单得多。
  1. 打开数据模型并选择属性的名称
  2. 打开数据模型检查器 (Command+Option+3)
  3. Attribute Type 设置为 Transformable
  4. Custom Class 设置为 NSAttributedString

Xcode 属性检查器截图

这就是全部步骤了,现在您可以像预期的那样在 Swift 代码中保存数据,无需修改生成的类或强制转换,例如: detailItem.content = textView.attributedText

0

是的,您可以通过简单的解决方案添加attributedText。

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

希望这可以帮助到您.. :)


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接