将NSAttributedString转换为纯文本

时间:2012-01-26 12:46:13

标签: cocoa nsattributedstring

我有一个NSData的实例,其中包含源自NSAttributedString的属性文本(NSTextView)。我想将属性字符串转换为普通字符串(NSString)而不进行任何格式化以进行一些文本分析(在转换时我无法访问原始NSTextView及其NSTextStorage实例)。

最好的方法是什么?

修改

出于好奇,我检查了结果:

[[[self textView] textStorage] words]

这对于进行一些文本分析似乎很方便。结果数组包含NSSubTextStorage的实例(下面的单词“Eastern”):

  

东{       NSFont =“\”LucidaGrande 11.00 pt。 P [](0x7ffcaae08330)fobj = 0x10a8472d0,spc = 3.48 \“”;       NSParagraphStyle =“对齐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.05,   HeaderLevel 0“;}

NSSubTextStorage可能是私有类,因为我找不到任何文档。它还保留所有格式。

3 个答案:

答案 0 :(得分:60)

如果我理解正确,您有NSData,说data,其中包含已编码的NSAttributedString。要扭转这个过程:

NSAttributedString *nas = [[NSAttributedString alloc] initWithData:data
                                                           options:nil
                                                documentAttributes:NULL
                                                             error:NULL];

并获取没有属性的纯文本,然后执行:

NSString *str = [nas string];

答案 1 :(得分:9)

更新Swift 2.2 / Swift 3:

attributedText.string

答案 2 :(得分:2)

使用Swift 4和macOS 10.0+,NSAttributedString有一个名为string的属性。 string有以下声明:

var string: String { get }
  

接收者的角色内容为NSString个对象。

Apple还说明了string

  

不会从此属性的值中删除附件字符。 [...]

以下Playground代码显示了如何使用NSAttributedString的{​​{1}}属性来检索string实例的字符串内容:

NSAttributedString