将NSAttributedString转换为纯文本 [英] Transform an NSAttributedString to plain text

查看:112
本文介绍了将NSAttributedString转换为纯文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 NSData 实例,该实例包含源自的属性文本( NSAttributedString ) NSTextView 。我想将属性字符串转换为纯字符串( NSString ),而无需进行任何格式的文本分析(在转换时,我无权访问原始NSTextView

I have an instance of NSData containing attributed text (NSAttributedString) originating from an NSTextView. I want to convert the attributed string to a plain string (NSString) without any formatting to do some text analysis (at the moment of conversion I do not have access to the originating NSTextView nor its NSTextStorage instance).

什么是最好的方法?

编辑:

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

Out of curiosity I examined the result of:

[[[self textView] textStorage] words]

做一些文本分析。结果数组包含NSSubTextStorage的实例(单词 Eastern的下面示例):

which appeared to be a handy thing for doing some text analysis. The resulting array contains instances of NSSubTextStorage (example below of the word "Eastern"):


Eastern {
NSFont = \ \ LucidaGrande 11.00点。 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,制表符(\ \n 28L,\n 56L,\n 84L,\n 112L,\n

140L,\n 168L,\n 196L,\224L,\n 252L ,\n 280L,\n

308L,\n 336L\n),DefaultTabInterval 0,块(null),列表(null),
BaseWritingDirection -1,HyphenationFactor 0 ,TighteningFactor 0.05,
HeaderLevel 0; }

Eastern{ NSFont = "\"LucidaGrande 11.00 pt. P [] (0x7ffcaae08330) fobj=0x10a8472d0, spc=3.48\""; 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.05, HeaderLevel 0"; }

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

NSSubTextStorage is probably a private class as I could not find any documentation for it. It also retains all formatting.

推荐答案

如果我对您的理解正确,则您有一个 NSData ,例如 data ,其中包含编码的 NSAttributedString 。要逆转该过程,请执行以下操作:

If I understand you correctly you have an NSData, say data, containing an encoded NSAttributedString. To reverse the process:

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

然后获取没有属性的纯文本,然后执行以下操作:

and to get the plain text without attributes you then do:

NSString *str = [nas string];

这篇关于将NSAttributedString转换为纯文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆