我有NSString,我需要做NSAttributedString。
NSString类似于:
bvcx b vcxbcvx bcxvbcxv bvx xbc bcvx bxcv bcxv bcxv bcxv bcvx bcvx bcxvbcvx bvc bcvx bxcv{
NSFont = "\"LucidaGrande 24.00 pt. P [] (0x108768a80) fobj=0x108788880, spc=7.59\"";
NSParagraphStyle = "Alignment 4, 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";
}它是UTF-8格式的NSAttributedString。有没有办法做到这一点?
发布于 2013-05-04 02:24:14
您说您从现有的NSAttributedString创建了输入字符串,如下所示:
[NSString stringWithFormat:@"%@", nsattributedstring]%@格式说明符将description消息发送到nsattributedstring对象。description方法不是用来生成可以轻松转换回NSAttributedString对象的字符串的。它的设计目的是帮助程序员调试他们的代码。
将对象转换为字符串或字节数组,以便稍后可以将其转换回对象的过程称为serialization.使用%@或description方法通常不是执行序列化的好方法。如果您确实想反序列化由description方法创建的字符串,则必须编写自己的解析器。据我所知,目前还没有这方面的API。
相反,Cocoa提供了一个用于序列化和反序列化对象的系统。可以使用此系统序列化的对象符合NSCoding协议。NSAttributedString对象符合NSCoding。因此,尝试以这种方式序列化原始的属性字符串:
NSMutableData *data = [NSKeyedArchiver archivedDataWithRootObject:nsattributedstring];在需要的地方保存data (它是非人类可读的二进制文件,而不是UTF-8)。当您需要重新创建属性字符串时,请执行以下操作:
NSAttributedString *fancyText = [NSKeyedUnarchiver unarchiveObjectWithData:data];如果您是在OS X (而不是iOS)上编程,那么您还有另一种选择。您可以使用RTFFromRange:documentAttributes: method (省略附件)或RTFDFromRange:documentAttributes: method (包含附件)将属性字符串转换为RTF (富文本格式),这种格式非常易于阅读。然后,您可以使用initWithRTF:documentAttributes:或initWithRTFD:documentAttributes:将RTF数据转换回属性字符串。这些方法在iOS上不可用。
如果是针对iOS 7.0或更高版本的进行编程,则可以使用-dataFromRange:documentAttributes:error:或fileWrapperFromRange:documentAttributes:error:将属性字符串转换为RTF/RTFD。您需要在文档属性中将NSDocumentTypeDocumentAttribute设置为NSRTFTextDocumentType或NSRTFDTextDocumentType。使用initWithData:options:documentAttributes:error:或initWithFileURL:options:documentAttributes:error:将其转换回NSAttributedString。这些方法是NSAttributedString UIKit Additions的一部分。
https://stackoverflow.com/questions/16364249
复制相似问题